Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Silent login #3

Merged
merged 18 commits into from
Sep 9, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 10 additions & 10 deletions dist/appid.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion errors/AppIDError.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
class AppIDError extends Error {
constructor({error, description}) {
super(description);
super(description || error);
this.error = error;
this.description = description;
}
Expand Down
2 changes: 2 additions & 0 deletions errors/IFrameError.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
class IFrameError extends Error {}
module.exports = IFrameError;
11 changes: 11 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,17 @@
"test": "mocha",
"coverage": "nyc --reporter=lcov mocha"
},
"nyc": {
"all": true,
"include": [
"src/*.js"
],
"exclude": [
"**/PopupController.js",
"**/IFrameController.js",
"**/OpenIDConfigurationResource.js"
]
},
"dependencies": {
"jsrsasign": "^8.0.12",
"node-fetch": "^2.6.0"
Expand Down
22 changes: 18 additions & 4 deletions sample/public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -27,29 +27,43 @@
</div>
<script type='text/javascript' src="appid.js"></script>
<script>
function showError(e) {
console.error(e);
document.getElementById('error').textContent = e;
document.getElementById('login').setAttribute('class', 'button');
}

(async function () {
const appID = new AppID();
try {
await appID.init({
clientId: '<SPA_CLIENT_ID>',
discoveryEndpoint: '<WELL_KNOWN_ENDPOINT>'
});
document.getElementById('login').setAttribute('class', 'button');
} catch (e) {
console.error(e);
document.getElementById('error').textContent = e;
}

try {
const tokens = await appID.silentSignin();
if (tokens) {
document.getElementById('id_token').textContent = JSON.stringify(tokens.idTokenPayload);
}
} catch (e) {
showError(e);
}
document.getElementById('login').addEventListener('click', async () => {
document.getElementById('login').setAttribute('class', 'hidden');
document.getElementById('error').textContent = '';
try {
const tokens = await appID.signinWithPopup();
let userInfo = await appID.getUserInfo(tokens.accessToken);
document.getElementById("login").style.display = 'none';
let decodeIDToken = tokens.idTokenPayload;
document.getElementById('welcome').innerHTML = 'Hello, ' + decodeIDToken.name;
document.getElementById('id_token').textContent = JSON.stringify(decodeIDToken);
document.getElementById('user_info').textContent = JSON.stringify(userInfo);
} catch (e) {
document.getElementById('error').textContent = e;
showError(e);
}
});
})()
Expand Down
35 changes: 35 additions & 0 deletions src/IFrameController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
const IFrameError = require('../errors/IFrameError');

class IFrameController {
constructor({w = window} = {}) {
this.window = w;
}

open(url) {
this.iFrame = this.window.document.createElement('iframe');
this.iFrame.src = url;
this.iFrame.width = 0;
this.iFrame.height = 0;
this.window.document.body.appendChild(this.iFrame);
}

remove() {
window.document.body.removeChild(this.iFrame);
}

async waitForMessage({messageType}) {
return new Promise((resolve, reject) => {
const timer = setInterval(() => {
reject(new IFrameError('Silent sign-in timed out'));
}, 5 * 1000);
window.addEventListener('message', (message) => {
if (!message.data || message.data.type !== messageType) {
return;
}
clearInterval(timer);
resolve(message);
});
});
}
}
module.exports = IFrameController;
11 changes: 1 addition & 10 deletions src/PopupController.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,6 @@ class PopupController {
}
};

openIFrame(url) {
this.iFrame = this.window.document.createElement('iframe');
this.iFrame.src = url;
this.iFrame.width = 0;
this.iFrame.height = 0;

window.document.body.appendChild(this.iFrame);
}

navigate({authUrl}) {
this.popup.location.href = authUrl;
};
Expand All @@ -41,7 +32,7 @@ class PopupController {
reject(new PopupError('Popup closed'));
}
}, 1000);
window.addEventListener('message', message => {
window.addEventListener('message', (message) => {
if (!message.data || message.data.type !== messageType) {
return;
}
Expand Down
2 changes: 2 additions & 0 deletions src/constants.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,13 @@ module.exports = {
INVALID_NONCE: 'Invalid nonce',
EXPIRED_TOKEN: 'Expired token',
INVALID_STATE: 'Invalid state',
INVALID_ORIGIN: 'Invalid origin',
INVALID_TOKEN: 'Invalid token',
MISSING_PUBLIC_KEY: 'Cannot find public key',
INVALID_ACCESS_TOKEN: 'Access token must be a string',
RESPONSE_TYPE: 'code',
RESPONSE_MODE: 'web_message',
PROMPT: 'none',
SCOPE: 'openid',
STATE_LENGTH: 20,
NONCE_LENGTH: 20,
Expand Down
88 changes: 67 additions & 21 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const Utils = require('./utils');
const RequestHandler = require('./RequestHandler');
const PopupController = require('./PopupController');
const IFrameController = require('./IFrameController');
const OpenIdConfigurationResource = require('./OpenIDConfigurationResource');
const TokenValidator = require('./TokenValidator');
const rs = require('jsrsasign');
Expand All @@ -11,19 +12,23 @@ class AppID {
constructor(
{
popup = new PopupController(),
iframe = new IFrameController(),
tokenValidator = new TokenValidator(),
openID = new OpenIdConfigurationResource(),
utils = new Utils(),
requestHandler = new RequestHandler(),
w = window
w = window,
url = URL
} = {}) {

this.popup = popup;
this.iframe = iframe;
this.tokenValidator = tokenValidator;
this.openIdConfigResource = openID;
this.utils = utils;
this.request = requestHandler.request;
this.window = w;
this.URL = url;
}

async init({clientId, discoveryEndpoint}) {
Expand All @@ -32,6 +37,33 @@ class AppID {
}

async signinWithPopup() {
const {codeVerifier, nonce, state, authUrl} = this.getAuthParams();

this.popup.open();
this.popup.navigate({authUrl});
const message = await this.popup.waitForMessage({messageType: 'authorization_response'});
this.popup.close();

this.verifyMessage({message, state});

let authCode = message.data.code;

return await this.exchangeTokens({authCode, codeVerifier, nonce});
}

async getUserInfo(accessToken) {
if (typeof accessToken !== 'string') {
throw new AppIDError({description: constants.INVALID_ACCESS_TOKEN});
}

return await this.request(this.openIdConfigResource.getUserInfoEndpoint(), {
headers: {
'Authorization': 'Bearer ' + accessToken
}
});
}

getAuthParams({prompt} = {}) {
const codeVerifier = this.utils.getRandomString(constants.CODE_VERIFIER_LENGTH);
const codeChallenge = this.utils.sha256(codeVerifier);
const nonce = this.utils.getRandomString(constants.NONCE_LENGTH);
Expand All @@ -45,38 +77,51 @@ class AppID {
code_challenge_method: constants.CHALLENGE_METHOD,
redirect_uri: this.window.origin,
response_mode: constants.RESPONSE_MODE,
nonce: nonce,
scope: constants.SCOPE
nonce,
scope: constants.SCOPE,
prompt
};

const authUrl = this.openIdConfigResource.getAuthorizationEndpoint() + '?' + this.utils.buildParams(authParams);
return {
codeVerifier,
nonce,
state,
authUrl
};
}

this.popup.open();
this.popup.navigate({authUrl});
const message = await this.popup.waitForMessage({messageType: 'authorization_response'});
this.popup.close();

if (message.data.error && message.data.description) {
throw new AppIDError({description: message.data.description, error: message.data.error})
verifyMessage({message, state}) {
if (message.data.error || message.data.error_description) {
throw new AppIDError({description: message.data.error_description, error: message.data.error});
}

if (rs.b64utos(message.data.state) !== state) {
throw new AppIDError({description: constants.INVALID_STATE});
}
let authCode = message.data.code;

return await this.exchangeTokens({authCode, codeVerifier, nonce});
let messageOrigin = message.origin;
let oauthOrigin = new this.URL(this.openIdConfigResource.getAuthorizationEndpoint()).origin;
if (messageOrigin !== oauthOrigin) {
throw new AppIDError({description: constants.INVALID_ORIGIN});
}
}

async getUserInfo(accessToken) {
if (typeof accessToken !== 'string') {
throw new AppIDError({description: constants.INVALID_ACCESS_TOKEN});
async silentSignin() {
const {codeVerifier, nonce, state, authUrl} = this.getAuthParams({prompt: constants.PROMPT});

this.iframe.open(authUrl);

let message;
try {
message = await this.iframe.waitForMessage({messageType: 'authorization_response'});
} finally {
this.iframe.remove();
}

return await this.request(this.openIdConfigResource.getUserInfoEndpoint(), {
headers: {
'Authorization': 'Bearer ' + accessToken
}
});
this.verifyMessage({message, state});

let authCode = message.data.code;
return await this.exchangeTokens({authCode, codeVerifier, nonce});
}

async exchangeTokens({authCode, nonce, codeVerifier}) {
Expand Down Expand Up @@ -120,4 +165,5 @@ class AppID {
return {accessToken: tokens.access_token, accessTokenPayload, idToken: tokens.id_token, idTokenPayload}
}
}

module.exports = AppID;
Loading