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

feat(@aws-amplify/auth): Easier Federation with OAuth #3005

Merged
merged 17 commits into from
Apr 8, 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
345 changes: 292 additions & 53 deletions packages/auth/__tests__/auth-unit-test.ts

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions packages/auth/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,8 @@
"dependencies": {
"@aws-amplify/cache": "^1.0.25",
"@aws-amplify/core": "^1.0.25",
"amazon-cognito-auth-js": "^1.3.2",
"amazon-cognito-identity-js": "3.0.11-unstable.0"
"amazon-cognito-identity-js": "^3.0.10",
"crypto-js": "^3.1.9-1"
},
"jest": {
"transform": {
Expand Down
360 changes: 223 additions & 137 deletions packages/auth/src/Auth.ts

Large diffs are not rendered by default.

285 changes: 285 additions & 0 deletions packages/auth/src/OAuth/OAuth.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,285 @@
/*
* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/


import { parse } from 'url'; // Used for OAuth parsing of Cognito Hosted UI
import { launchUri } from './urlOpener';
import * as oAuthStorage from './oauthStorage';

import {
OAuthOpts,
isCognitoHostedOpts,
CognitoHostedUIIdentityProvider
} from '../types/Auth';

import {
ConsoleLogger as Logger,
Hub
} from '@aws-amplify/core';

const SHA256 = require("crypto-js/sha256");
const Base64 = require("crypto-js/enc-base64");

const AMPLIFY_SYMBOL = ((typeof Symbol !== 'undefined' && typeof Symbol.for === 'function') ?
Symbol.for('amplify_default') : '@@amplify_default') as Symbol;

const dispatchAuthEvent = (event:string, data:any, message:string) => {
Hub.dispatch('auth', { event, data, message }, 'Auth', AMPLIFY_SYMBOL);
};

const logger = new Logger('OAuth');

export default class OAuth {

private _urlOpener;
private _config;
private _cognitoClientId;
private _scopes;

constructor({
config,
cognitoClientId,
scopes = []
}: {
scopes: string[],
config: OAuthOpts,
cognitoClientId: string
}) {
this._urlOpener = config.urlOpener || launchUri;
this._config = config;
this._cognitoClientId = cognitoClientId;
this._scopes = scopes;
}

public oauthSignIn(
responseType = 'code',
domain: string,
redirectSignIn: string,
clientId: string,
provider: CognitoHostedUIIdentityProvider | string) {

const state = this._generateState(32);
oAuthStorage.setState(state);

const pkce_key = this._generateRandom(128);
oAuthStorage.setPKCE(pkce_key);

const code_challenge = this._generateChallenge(pkce_key);
const code_challenge_method = 'S256';

const queryString = Object.entries({
redirect_uri: redirectSignIn,
response_type: responseType,
client_id: clientId,
identity_provider: provider,
scopes: this._scopes,
state,
...(responseType === 'code'?{code_challenge}:{}),
...(responseType === 'code'?{code_challenge_method}:{})
}).map(([k,v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`).join('&');

const URL = `https://${domain}/oauth2/authorize?${queryString}`;
logger.debug(`Redirecting to ${URL}`);
this._urlOpener(URL, redirectSignIn);
}

private async _handleCodeFlow(currentUrl: string) {
/* Convert URL into an object with parameters as keys
{ redirect_uri: 'http://localhost:3000/', response_type: 'code', ...} */
const { code } = (parse(currentUrl).query || '')
.split('&')
.map((pairings) => pairings.split('='))
.reduce((accum, [k, v]) => ({ ...accum, [k]: v }), { code: undefined });

if (!code) { return; }


const oAuthTokenEndpoint = 'https://' + this._config.domain + '/oauth2/token';

dispatchAuthEvent(
'codeFlow',
{},
`Retrieving tokens from ${oAuthTokenEndpoint}`
);

const client_id = isCognitoHostedOpts(this._config)
? this._cognitoClientId
: this._config.clientID;

const redirect_uri = isCognitoHostedOpts(this._config)
? this._config.redirectSignIn
: this._config.redirectUri;

const code_verifier = oAuthStorage.getPKCE();

const oAuthTokenBody = {
grant_type: 'authorization_code',
code,
client_id,
redirect_uri,
code_verifier
};

logger.debug(`Calling token endpoint: ${oAuthTokenEndpoint} with`, oAuthTokenBody);

const body = Object.entries(oAuthTokenBody)
.map(([k, v]) =>`${encodeURIComponent(k)}=${encodeURIComponent(v)}`)
.join('&');

const { access_token, refresh_token, id_token, error } = await (await fetch(oAuthTokenEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: typeof URLSearchParams !== 'undefined' ? new URLSearchParams(body) : body
}) as any).json();

if (error) {
throw new Error(error);
}

return {
accessToken: access_token,
refreshToken: refresh_token,
idToken: id_token
};
}

private async _handleImplicitFlow(currentUrl: string) {

const { id_token, access_token } = parse(currentUrl).hash
.substr(1) // Remove # from returned code
.split('&')
.map((pairings) => pairings.split('='))
.reduce((accum, [k, v]) => ({ ...accum, [k]: v }), {
id_token: undefined, access_token: undefined
});

dispatchAuthEvent(
'implicitFlow',
{},
`Got tokens from ${currentUrl}`
);
logger.debug(`Retrieving implicit tokens from ${currentUrl} with`);

return {
accessToken: access_token,
idToken: id_token,
refreshToken: null
};
}

public async handleAuthResponse(currentUrl?: string) {
const urlParams = currentUrl ? {
...(parse(currentUrl).hash || '#').substr(1)
.split('&')
.map(entry => entry.split('='))
.reduce((acc, [k, v]) => (acc[k] = v, acc), {}),
...(parse(currentUrl).query || '')
.split('&')
.map(entry => entry.split('='))
.reduce((acc, [k, v]) => (acc[k] = v, acc), {})
} as any : {};
const { error, error_description } = urlParams;

if (error) {
throw new Error(error_description);
}

this._validateState(urlParams);

logger.debug(`Starting ${this._config.responseType} flow with ${currentUrl}`);
if (this._config.responseType === 'code') {
return this._handleCodeFlow(currentUrl);
} else {
return this._handleImplicitFlow(currentUrl);
}
}

private _validateState(urlParams: any) {
if (!urlParams) { return; }

const savedState = oAuthStorage.getState();
const { state: returnedState } = urlParams;

if (savedState !== returnedState) {
throw new Error('Invalid state in OAuth flow');
}
}

public async signOut() {
let oAuthLogoutEndpoint = 'https://' + this._config.domain + '/logout?';

const client_id = isCognitoHostedOpts(this._config)
? this._cognitoClientId
: this._config.oauth.clientID;

const signout_uri = isCognitoHostedOpts(this._config)
? this._config.redirectSignOut
: this._config.returnTo;

oAuthLogoutEndpoint += Object.entries({
client_id,
logout_uri: encodeURIComponent(signout_uri)
}).map(([k, v]) => `${k}=${v}`).join('&');

dispatchAuthEvent(
'oAuthSignOut',
{oAuth: 'signOut'},
`Signing out from ${oAuthLogoutEndpoint}`
);
logger.debug(`Signing out from ${oAuthLogoutEndpoint}`);

this._urlOpener(oAuthLogoutEndpoint);
}

private _generateState(length: number) {
let result = '';
let i = length;
const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
for (; i > 0; --i) result += chars[Math.round(Math.random() * (chars.length - 1))];
return result;
}

private _generateChallenge(code:string) {
return this._base64URL(SHA256(code));
}

private _base64URL(string) {
return string.toString(Base64).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
}

private _generateRandom(size: number) {
const CHARSET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~';
const buffer = new Uint8Array(size);
if (typeof window !== 'undefined' && !!(window.crypto)) {
window.crypto.getRandomValues(buffer);
} else {
for (let i = 0; i < size; i += 1) {
buffer[i] = (Math.random() * CHARSET.length) | 0;
}
}
return this._bufferToString(buffer);
}

private _bufferToString(buffer: Uint8Array) {
const CHARSET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
const state = [];
for (let i = 0; i < buffer.byteLength; i += 1) {
const index = buffer[i] % CHARSET.length;
state.push(CHARSET[index]);
}
return state.join('');
}
}

42 changes: 42 additions & 0 deletions packages/auth/src/OAuth/oauthStorage.native.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
/*
* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/

const obj:{
oauth_state?: string,
ouath_pkce_key?: string
} = {};

export const setState = (state:string) =>{
obj.oauth_state = state;
};

export const getState = () => {
const oauth_state = obj.oauth_state;
obj.oauth_state = undefined;
return oauth_state;
};

export const setPKCE = (private_key:string) =>{
obj.ouath_pkce_key = private_key;
};

export const getPKCE = () => {
const ouath_pkce_key = obj.ouath_pkce_key;
obj.ouath_pkce_key = undefined;
return ouath_pkce_key;
};

export const clearAll = () => {
obj.ouath_pkce_key = undefined;
obj.oauth_state = undefined;
};
37 changes: 37 additions & 0 deletions packages/auth/src/OAuth/oauthStorage.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/*
* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/

export const setState = (state:string) =>{
window.sessionStorage.setItem('oauth_state', state);
};

export const getState = () => {
const oauth_state = window.sessionStorage.getItem('oauth_state');
window.sessionStorage.removeItem('oauth_state');
return oauth_state;
};

export const setPKCE = (private_key:string) =>{
window.sessionStorage.setItem('ouath_pkce_key', private_key);
};

export const getPKCE = () => {
const ouath_pkce_key = window.sessionStorage.getItem('ouath_pkce_key');
window.sessionStorage.removeItem('ouath_pkce_key');
return ouath_pkce_key;
};

export const clearAll = () => {
window.sessionStorage.removeItem('ouath_pkce_key');
window.sessionStorage.removeItem('oauth_state');
};
16 changes: 16 additions & 0 deletions packages/auth/src/OAuth/urlOpener.native.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
/*
* Copyright 2017-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with
* the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/

import { Linking } from 'react-native';

export const launchUri = (url) => Linking.openURL(url);
Loading