-
-
Save fluency03/47199b1db12e47fe5b9f64ee81c90c24 to your computer and use it in GitHub Desktop.
Simplified Native OAuth2.0 Application Login CLI implementation
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
/* eslint-disable no-console, camelcase */ | |
const server = require('http').createServer().listen(0); | |
const { Issuer, generators } = require('openid-client'); | |
const open = require('open'); | |
server.removeAllListeners('request'); | |
const { ISSUER = 'https://op.panva.cz' } = process.env; | |
server.once('listening', () => { | |
(async () => { | |
const issuer = await Issuer.discover(ISSUER); | |
const { address, port } = server.address(); | |
const hostname = address === '::' ? '[::1]' : address; | |
const client = await issuer.Client.register({ | |
redirect_uris: [`http://${hostname}`], | |
application_type: 'native', | |
token_endpoint_auth_method: 'none', | |
}); | |
const code_verifier = generators.codeVerifier(); | |
const code_challenge = generators.codeChallenge(code_verifier); | |
const redirect_uri = `http://${address === '::' ? '[::1]' : address}:${port}`; | |
server.on('request', async (req, res) => { | |
res.setHeader('connection', 'close'); | |
const params = client.callbackParams(req); | |
if (Object.keys(params).length) { | |
const tokenSet = await client.callback( | |
redirect_uri, params, { code_verifier, response_type: 'code' }, | |
); | |
console.log('got', tokenSet); | |
console.log('id token claims', tokenSet.claims()); | |
const userinfo = await client.userinfo(tokenSet); | |
console.log('userinfo', userinfo); | |
res.end('you can close this now'); | |
server.close(); | |
} | |
}); | |
await open(client.authorizationUrl({ | |
redirect_uri, | |
code_challenge, | |
code_challenge_method: 'S256', | |
scope: 'openid email', | |
}), { wait: false }); | |
})().catch((err) => { | |
console.error(err); | |
process.exitCode = 1; | |
server.close(); | |
}); | |
}); |
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": "pg", | |
"version": "1.0.0", | |
"description": "", | |
"main": "codeflow.js", | |
"scripts": { | |
"test": "echo \"Error: no test specified\" && exit 1" | |
}, | |
"author": "", | |
"license": "ISC", | |
"dependencies": { | |
"open": "^7.0.0", | |
"openid-client": "^3.8.3" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment