Last active
July 17, 2020 10:12
-
-
Save steffen/b9bd885f3befb88f40d89910f50ae645 to your computer and use it in GitHub Desktop.
GitHub Login OAuth example with Node.js and Express
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 { createOAuthAppAuth } = require("@octokit/auth-oauth-app") | |
const express = require('express') | |
const app = express() | |
const port = 3000 | |
const clientId = '123' | |
const clientSecret = '456' | |
const authUrl = `https://github.com/login/oauth/authorize?client_id=${clientId}&redirect_uri=http://localhost:3000/login` | |
const body = `<button onclick="location.href='${authUrl}'">Login with GitHub</button>` | |
/** | |
* 1. Open http://localhost:3000/ | |
* 2. Click on "Login with GitHub" -> Authorize App | |
* 3. You'll be redirected to http://localhost:3000/login?code=123samplecode | |
* 4. In the browser console run: `response = await fetch(`/login?code=${(new URLSearchParams(window.location.search)).get('code')}`, { method: 'POST' }); await response.json()` | |
* 5. Browser console should output object with `token` that can now be used to authenticate with the GitHub API | |
*/ | |
/** | |
* Page with "Login with GitHub" button | |
*/ | |
app.get('/', (req, res) => res.send(body)) | |
/** | |
* Redirect page: Run step 4 on this page | |
*/ | |
app.get('/login', (req, res) => { | |
res.send('Logging in') | |
}) | |
/** | |
* This is the POST endpoint that gets the authentication token from GitHub and which we call in step 4 | |
*/ | |
app.post('/login', async (req, res) => { | |
const auth = createOAuthAppAuth({ | |
clientId, | |
clientSecret | |
}) | |
console.log(auth) | |
const tokenAuthentication = await auth({ | |
type: 'token', | |
code: req.query.code | |
}) | |
console.log(tokenAuthentication) | |
res.send(tokenAuthentication) | |
}) | |
app.listen(port, () => console.log(`Example app listening at http://localhost:${port}`)) |
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
{ | |
"name": "github-login-oauth-example", | |
"version": "1.0.0", | |
"description": "", | |
"main": "index.js", | |
"scripts": { | |
"start": "nodemon index.js", | |
"test": "echo \"Error: no test specified\" && exit 1" | |
}, | |
"author": "", | |
"license": "ISC", | |
"dependencies": { | |
"@octokit/auth-oauth-app": "^3.0.5", | |
"express": "^4.17.1", | |
"nodemon": "^2.0.4" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment