Skip to content

Instantly share code, notes, and snippets.

@panva
Last active April 29, 2021 09:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save panva/429e0c646eb730079fe0a0070c160e1d to your computer and use it in GitHub Desktop.
Save panva/429e0c646eb730079fe0a0070c160e1d to your computer and use it in GitHub Desktop.
Simple Native OAuth2.0 Application Login CLI implementation

Simple Native OAuth2.0 Application Login CLI implementation

run

npx https://gist.github.com/panva/429e0c646eb730079fe0a0070c160e1d
#!/usr/bin/env node
/* 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": "index.js",
"bin": "./index.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