node-samples
node-samples copied to clipboard
adminSDK samples using deprecated OAuth out-of-band flow.
Expected Behaviour
The adminSDK example files should work as they are referenced on the google documentation https://developers.google.com/admin-sdk/directory/v1/quickstart/nodejs
Actual Behavior
Due to the new google oauth changes https://developers.googleblog.com/2022/02/making-oauth-flows-safer.html#instructions-oob a callback service is required if using oauth flows - failing to provide this results in a 400 error:
The application should be updated to have a localhost callback that is still supported by the google oauth flow policy changes and not a deprecated (and now not working) implementation.
Authorization Error
Error 400: invalid_request
You can't sign in to this app because it doesn't comply with Google's OAuth 2.0 policy for keeping apps secure.
You can let the app developer know that this app doesn't comply with one or more Google validation rules.
Request Details
The content in this section has been provided by the app developer. This content has not been reviewed or verified by Google.
If you’re the app developer, make sure that these request details comply with Google policies.
redirect_uri: urn:ietf:wg:oauth:2.0:oob
For a lot of people this is their starting place using google APIs (https://developers.google.com/admin-sdk/directory/v1/quickstart/nodejs ) and for the referenced examples to be so broken is a bad look.
Steps to Reproduce the Problem
- Follow steps in https://developers.google.com/admin-sdk/directory/v1/quickstart/nodejs using a newly created oauth application credentials.json
- 400 error will be received and no temporary token will be provided to supply to the cli.
Same for Google Sheets Quickstart, got this email: "[Action Required] Migrate your OAuth out-of-band flow to an alternative method before Oct. 3, 2022"
This is my solution (in getNewToken(), start server, resolve promise once we get code and stop the server; also uses open npm package to open auth link in browser):
import fs from "fs";
import { google } from "googleapis";
import { Credentials, OAuth2Client } from "google-auth-library";
import path from "path";
import http from "http";
import open from "open";
import { URL, URLSearchParams } from "url";
// If modifying these scopes, delete token.json.
const SCOPES = ["https://www.googleapis.com/auth/spreadsheets"];
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
const TOKEN_PATH = path.join(__dirname, "token.json");
// Load client secrets from a local file.
const CREDENTIALS_PATH = path.join(__dirname, "credentials.json");
const credentials = fs.readFileSync(CREDENTIALS_PATH, "utf-8");
/**
* Create an OAuth2 client with the given credentials and returns it
* @param {Object} credentials The authorization client credentials.
*/
const authorize = async (credentials: {
installed: {
client_id: string;
project_id: string;
auth_uri: string;
token_uri: string;
auth_provider_x509_cert_url: string;
client_secret: string;
redirect_uris: string[];
};
}) => {
const { client_secret, client_id, redirect_uris } = credentials.installed;
const oAuth2Client = new google.auth.OAuth2(
client_id,
client_secret,
redirect_uris[0]
);
const getToken = async (): Promise<Credentials> => {
if (fs.existsSync(TOKEN_PATH)) {
// Check if we have previously stored a token.
return JSON.parse(fs.readFileSync(TOKEN_PATH, "utf-8"));
} else {
return getNewToken(oAuth2Client);
}
};
const token = await getToken();
oAuth2Client.setCredentials(token);
return oAuth2Client;
};
/**
* Get and store new token after prompting for user authorization
* @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
*/
const getNewToken = async (
oAuth2Client: OAuth2Client
): Promise<Credentials> => {
const authUrl = oAuth2Client.generateAuthUrl({
access_type: "offline",
scope: SCOPES,
});
console.log("Authorize this app by visiting this url:", authUrl);
open(authUrl);
const code = await new Promise<string>((resolve) => {
const server = http
.createServer((request, response) => {
const url = new URL(`http://localhost${request.url}`);
const code = new URLSearchParams(url.search).get("code");
if (code) {
response.end("Handling the code to your NodeJS app, check it...");
server.close();
resolve(code);
return;
}
response.end("waiting for code...");
})
.listen(19843);
});
let token: Credentials;
try {
token = (await oAuth2Client.getToken(code)).tokens;
} catch (error) {
throw `Error while trying to retrieve access token: ${error}`;
}
oAuth2Client.setCredentials(token);
// Store the token to disk for later program executions
fs.writeFileSync(TOKEN_PATH, JSON.stringify(token));
console.log("Token stored to", TOKEN_PATH);
return token;
};
export class GoogleSheets {
private oAuth2Client: OAuth2Client | undefined;
public async getOAuth2Client() {
if (this.oAuth2Client === undefined) {
this.oAuth2Client = await authorize(JSON.parse(credentials));
}
return this.oAuth2Client;
}
}
in credentials.json:
-"redirect_uris": ["urn:ietf:wg:oauth:2.0:oob", "http://localhost"]
+"redirect_uris": ["http://localhost:19843"]
This is a problem for all of the samples, not just adminSDK.
@sqrrrl (sorry if you are not the appropriate person to ping; I'm not sure who maintains this): All of the quickstart samples for node are currently broken because of this. This is particularly bad these are often the first place developers start. Any chance you can prioritize this, or ping someone who can?