Comments (3)
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"
from node-samples.
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"]
from node-samples.
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?
from node-samples.
Related Issues (20)
- Code sample response after add sheet is not accurate
- The API returned an error: Invalid Input HOT 1
- isTokenExpiring is not working, we need to refresh the token
- No authorization code HOT 2
- Access response with data field
- Dependency Dashboard
- V3 Upload to folder snippet parents value incorrect HOT 1
- Incorrect scopes url
- Filename issue HOT 1
- Documentation update HOT 1
- Cannot read properties of undefined (reading 'redirect_uris') at authenticate HOT 2
- [SyncRepoSettings bot] - Invalid config file
- I am not able to create folder in google drive using google drive APIs HOT 1
- Issue Title
- Incorrect code in drive_move_file_to_folder node sample
- getting random localhost urls with google gmail nodejs quickstart HOT 2
- bugs: Failed to get started with gmail Guide HOT 3
- "The API returned an error: GaxiosError: Invalid Credentials" while calling Gmail API
- how to authentication in sheets using service accounts
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from node-samples.