Last active
April 2, 2019 12:02
-
-
Save Frenchcooc/93e48074ad4a00447ab4d83cd1c19bd9 to your computer and use it in GitHub Desktop.
Fast expressjs app to retrieve OAuth tokens
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Quick express-app to retrieve OAuth credentials | |
* | |
* Run it with $ node index.js | |
*/ | |
const express = require('express') | |
const request = require('request') | |
const app = express() | |
app.set('port', 3000) | |
const CLIENT_ID = 'YOUR_CLIENT_ID' | |
const CLIENT_SECRET = 'YOUR_CLIENT_SECRET' | |
const SCOPES = 'YOUR_SCOPES' | |
const AUTHORIZE_URI = 'https://example.com/api/authorize' | |
const TOKEN_URI = 'https://example.com/api/get_token' | |
const REDIRECT_URI = `http://localhost:${app.get('port')}/callback` | |
app.get('/', (req, res) => { | |
// Build the auth URL | |
const authUrl = AUTHORIZE_URI + | |
`?client_id=${encodeURIComponent(CLIENT_ID)}` + | |
`&scope=${encodeURIComponent(SCOPES)}` + | |
`&redirect_uri=${encodeURIComponent(REDIRECT_URI)}` | |
// Redirect the user | |
return res.redirect(authUrl) | |
}) | |
app.get('/callback', (req, res) => { | |
if (!req.query.code) { | |
return res.send('Something went wrong') | |
} | |
// Exchange authorization code for tokens | |
const formData = { | |
grant_type: 'authorization_code', | |
client_id: CLIENT_ID, | |
client_secret: CLIENT_SECRET, | |
redirect_uri: REDIRECT_URI, | |
code: req.query.code | |
} | |
request.post(TOKEN_URI, { form: formData }, (err, data) => { | |
// Handle the returned tokens | |
res.send(data) | |
}) | |
}) | |
app.listen(app.get('port'), () => { console.log(`Serving! http://localhost:${app.get('port')}`) } ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment