Last active
November 1, 2019 09:22
-
-
Save guilhermebkel/fdf79db94a559b14066c713824a1b87b to your computer and use it in GitHub Desktop.
oauth2-boilerplate-nodejs
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
const request = require('request') | |
const cors = require('cors') | |
const express = require('express') | |
const app = express() | |
app.use(cors()) | |
app.get('/oauth/login', login) | |
app.get('/oauth/callback', callback) | |
app.listen(3333) | |
const Credentials = { | |
redirect_url: 'https://YOUR_SERVER' + '/oauth/callback', | |
client_id: 'YOUR_CLIENT_ID', | |
client_secret: 'YOUR_CLIENT_SECRET' | |
} | |
// Here you have to make the OAuthURL based on the service your going to use (like google, github, etc) so you can | |
// find information about how to do it properly on its own oauth docs. | |
const OAuthURL = `https://.../authorize?client_id=${Credentials.client_id}&redirect_uri=${Credentials.redirect_url}` | |
async function login(req, res) { | |
res.redirect(OAuthURL) | |
} | |
async function callback(req, res) { | |
let code = req.query.code || null | |
let authOptions = { | |
// Here you need to put the url you'll make the request to receive the access_token. | |
// Again you can find this url on the service docs. | |
url: 'https://.../login/oauth/access_token', | |
form: { | |
grant_type: 'authorization_code', | |
code, | |
client_id: Credentials.client_id, | |
client_secret: Credentials.client_secret, | |
redirect_uri: Credentials.redirect_url, | |
}, | |
headers: { | |
'Content-Type': 'multipart/form-data' | |
}, | |
json: true | |
} | |
request.post(authOptions, function (error, response, body) { | |
const access_token = body.access_token | |
res.redirect('https://YOUR_CLIENT_URL' + '/oauth?access_token=' + access_token) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment