Skip to content

Instantly share code, notes, and snippets.

@fluency03
Forked from panva/README.md
Created November 29, 2019 19:11
Show Gist options
  • Save fluency03/47199b1db12e47fe5b9f64ee81c90c24 to your computer and use it in GitHub Desktop.
Save fluency03/47199b1db12e47fe5b9f64ee81c90c24 to your computer and use it in GitHub Desktop.
Simplified Native OAuth2.0 Application Login CLI implementation
/* 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();
});
});
{
"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