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

[SDK-1790] use refresh_tokens with multiple audiences #521

Merged
merged 3 commits into from
Jul 14, 2020
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
32 changes: 15 additions & 17 deletions __tests__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -439,6 +439,8 @@ describe('Auth0', () => {

expect(utils.oauthToken).toHaveBeenCalledWith(
{
audience: undefined,
scope: 'openid profile email',
baseUrl: 'https://test.auth0.com',
client_id: TEST_CLIENT_ID,
code: TEST_CODE,
Expand Down Expand Up @@ -474,6 +476,7 @@ describe('Auth0', () => {
expect(utils.oauthToken).toHaveBeenCalledWith(
{
audience: undefined,
scope: 'openid profile email',
baseUrl: 'https://test.auth0.com',
client_id: TEST_CLIENT_ID,
code: TEST_CODE,
Expand All @@ -491,6 +494,8 @@ describe('Auth0', () => {
await auth0.loginWithPopup({ audience: 'test-audience' });
expect(utils.oauthToken).toHaveBeenCalledWith(
{
audience: 'test-audience',
scope: 'openid profile email',
baseUrl: 'https://test.auth0.com',
client_id: TEST_CLIENT_ID,
code: TEST_CODE,
Expand Down Expand Up @@ -1027,6 +1032,8 @@ describe('Auth0', () => {

expect(utils.oauthToken).toHaveBeenCalledWith(
{
audience: 'default',
scope: 'openid profile email',
baseUrl: 'https://test.auth0.com',
client_id: TEST_CLIENT_ID,
code: TEST_CODE,
Expand Down Expand Up @@ -1239,6 +1246,8 @@ describe('Auth0', () => {

expect(utils.oauthToken).toHaveBeenCalledWith(
{
audience: 'default',
scope: 'openid profile email',
baseUrl: 'https://test.auth0.com',
client_id: TEST_CLIENT_ID,
code: TEST_CODE,
Expand Down Expand Up @@ -1605,6 +1614,8 @@ describe('Auth0', () => {

expect(utils.oauthToken).toHaveBeenCalledWith(
{
audience: undefined,
scope: 'openid profile email offline_access',
baseUrl: 'https://test.auth0.com',
refresh_token: TEST_REFRESH_TOKEN,
client_id: TEST_CLIENT_ID,
Expand Down Expand Up @@ -1672,6 +1683,8 @@ describe('Auth0', () => {

expect(utils.oauthToken).toHaveBeenCalledWith(
{
audience: undefined,
scope: 'openid email offline_access',
baseUrl: 'https://test.auth0.com',
refresh_token: TEST_REFRESH_TOKEN,
client_id: TEST_CLIENT_ID,
Expand All @@ -1694,23 +1707,6 @@ describe('Auth0', () => {
}
});
});

it('falls back to the iframe method when an audience is specified', async () => {
const { auth0, utils } = await setup({
useRefreshTokens: true
});

await auth0.getTokenSilently({
audience: 'other-audience',
ignoreCache: true
});

expect(utils.runIframe).toHaveBeenCalledWith(
`https://test.auth0.com/authorize?${TEST_QUERY_PARAMS}${TEST_AUTH0_CLIENT_QUERY_STRING}`,
'https://test.auth0.com',
undefined
);
});
});
});

Expand Down Expand Up @@ -1920,6 +1916,8 @@ describe('Auth0', () => {

expect(utils.oauthToken).toHaveBeenCalledWith(
{
audience: 'test:audience',
scope: 'openid profile email test:scope',
baseUrl: 'https://test.auth0.com',
client_id: TEST_CLIENT_ID,
code: TEST_CODE,
Expand Down
61 changes: 60 additions & 1 deletion __tests__/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,17 @@ import {
DEFAULT_AUTHORIZE_TIMEOUT_IN_SECONDS,
DEFAULT_SILENT_TOKEN_RETRY_COUNT
} from '../src/constants';
import { MessageChannel } from 'worker_threads';
import unfetch from 'unfetch';
// @ts-ignore
import Worker from '../src/token.worker';

jest.mock('../src/token.worker');
jest.mock('unfetch');
const mockUnfetch = <jest.Mock>unfetch;
(<any>global).TextEncoder = TextEncoder;
(<any>global).MessageChannel = MessageChannel;
(<any>global).fetch = mockUnfetch;

afterEach(() => {
jest.resetAllMocks();
Expand Down Expand Up @@ -152,7 +158,7 @@ describe('utils', () => {
})
);
jest.spyOn(window, 'clearTimeout');
await fetchWithTimeout('https://test.com/', {}, undefined);
await fetchWithTimeout('https://test.com/', null, null, {}, undefined);
expect(clearTimeout).toBeCalledTimes(1);
});
});
Expand Down Expand Up @@ -288,6 +294,59 @@ describe('utils', () => {
expect(mockUnfetch.mock.calls[0][1].signal).not.toBeUndefined();
});

it('calls oauth/token with a worker with the correct url', async () => {
mockUnfetch.mockReturnValue(
new Promise(res =>
res({ ok: true, json: () => new Promise(ress => ress(true)) })
)
);
const worker = new Worker();
const spy = jest.spyOn(worker, 'postMessage');
const body = {
redirect_uri: 'http://localhost',
grant_type: 'authorization_code',
client_id: 'client_idIn',
code: 'codeIn',
code_verifier: 'code_verifierIn'
};

await oauthToken(
{
grant_type: 'authorization_code',
baseUrl: 'https://test.com',
client_id: 'client_idIn',
code: 'codeIn',
code_verifier: 'code_verifierIn',
audience: '__test_audience__',
scope: '__test_scope__'
},
worker
);

expect(mockUnfetch).toBeCalledWith('https://test.com/oauth/token', {
body: JSON.stringify(body),
headers: { 'Content-type': 'application/json' },
method: 'POST',
signal: abortController.signal
});

expect(mockUnfetch.mock.calls[0][1].signal).not.toBeUndefined();
expect(spy).toHaveBeenCalledWith(
{
body: JSON.stringify(body),
audience: '__test_audience__',
scope: '__test_scope__',
headers: {
'Content-type': 'application/json'
},
method: 'POST',
timeout: 10000,
url: 'https://test.com/oauth/token'
},
expect.arrayContaining([expect.anything()])
);
});

it('handles error with error response', async () => {
const theError = {
error: 'the-error',
Expand Down
122 changes: 97 additions & 25 deletions cypress/integration/getTokenSilently.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { shouldBe, whenReady } from '../support/utils';

describe('getTokenSilently', function() {
describe('getTokenSilently', function () {
beforeEach(cy.resetTests);
afterEach(cy.logout);

it('returns an error when not logged in', function(done) {
it('returns an error when not logged in', function (done) {
whenReady().then(win =>
win.auth0.getTokenSilently().catch(error => {
shouldBe('login_required', error.error);
Expand Down Expand Up @@ -48,7 +48,8 @@ describe('getTokenSilently', function() {
cy.toggleSwitch('local-storage');

cy.login().then(() => {
cy.reload().wait(5000);
cy.reload();
cy.get('#loaded', { timeout: 5000 });

cy.get('[data-cy=get-token]')
.click()
Expand All @@ -67,29 +68,100 @@ describe('getTokenSilently', function() {
});
});
});
});
});

describe('when using refresh tokens', () => {
it('retrieves an access token using a refresh token', () => {
cy.server();

return whenReady().then(win => {
cy.toggleSwitch('local-storage');
cy.toggleSwitch('use-cache');
cy.toggleSwitch('refresh-tokens');

cy.login().then(() => {
cy.route({
method: 'POST',
url: '**/oauth/token'
}).as('tokenApiCheck');

cy.get('[data-cy=get-token]')
.should('have.length', 1)
.click()
.wait(500)
.get('[data-cy=access-token]')
.should('have.length', 2);

cy.wait('@tokenApiCheck').then(xhr => {
console.log(xhr);
assert.equal(
xhr.request.body.grant_type,
'refresh_token',
'used a refresh_token to get an access_token'
);
});
});
});
});

it('retrieves an access token for another audience using a refresh token', () => {
cy.server();

return whenReady().then(win => {
cy.toggleSwitch('local-storage');
cy.toggleSwitch('use-cache');
cy.toggleSwitch('refresh-tokens');

cy.login().then(() => {
cy.route({
method: 'POST',
url: '**/oauth/token'
}).as('tokenApiCheck');

cy.get('[data-cy=get-token]')
.click()
.wait(500)
.get('[data-cy=access-token]')
.should('have.length', 2);

cy.wait('@tokenApiCheck').then(xhr => {
console.log(xhr);
assert.equal(
xhr.request.body.grant_type,
'refresh_token',
'used a refresh_token to get an access_token'
);
});

cy.get('[data-cy=get-token-1]')
.click()
.wait(500)
.get('[data-cy=access-token-1]')
.should('have.length', 1);

cy.wait('@tokenApiCheck').then(xhr => {
console.log(xhr);
assert.equal(
xhr.request.body.grant_type,
'authorization_code',
'get a refresh_token for a new audience with an iframe'
);
});

cy.get('[data-cy=get-token-1]')
.click()
.wait(500)
.get('[data-cy=access-token-1]')
.should('have.length', 2);

describe('when using refresh tokens', () => {
/**
* This test will fail with a 'consent_required' error when running on localhost, but the fact that it does
* proves that the iframe method was attempted even though we're supposed to be using refresh tokens.
*/
it.skip('attempts to retrieve an access token by falling back to the iframe method', () => {
return whenReady().then(win => {
cy.toggleSwitch('local-storage');
cy.toggleSwitch('use-cache');

cy.login().then(() => {
cy.toggleSwitch('refresh-tokens').wait(1000);
win.localStorage.clear();

cy.get('[data-cy=get-token]')
.click()
.wait(500)
.get('[data-cy=access-token]')
.should('have.length', 1);

cy.get('[data-cy=error]').should('contain', 'consent_required');
});
cy.wait('@tokenApiCheck').then(xhr => {
console.log(xhr);
assert.equal(
xhr.request.body.grant_type,
'refresh_token',
'use a refresh_token to get a new access_token'
);
});
});
});
Expand Down
9 changes: 3 additions & 6 deletions cypress/support/commands.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,7 @@ Cypress.Commands.add('login', () => {
.clear()
.type('[email protected]');

cy.get('.auth0-lock-input-password .auth0-lock-input')
.clear()
.type('1234');
cy.get('.auth0-lock-input-password .auth0-lock-input').clear().type('1234');
cy.get('.auth0-lock-submit').click();

return whenReady().then(() => {
Expand All @@ -48,14 +46,13 @@ Cypress.Commands.add('loginNoCallback', () => {
cy.get('.auth0-lock-input-username .auth0-lock-input')
.clear()
.type('[email protected]');
cy.get('.auth0-lock-input-password .auth0-lock-input')
.clear()
.type('1234');
cy.get('.auth0-lock-input-password .auth0-lock-input').clear().type('1234');
cy.get('.auth0-lock-submit').click();
});

Cypress.Commands.add('resetTests', () => {
cy.visit('http://localhost:3000');
cy.get('#reset-config').click();
cy.get('#logout').click();
cy.window().then(win => win.localStorage.clear());
});
6 changes: 2 additions & 4 deletions cypress/support/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,5 @@ module.exports.shouldNotBeUndefined = e => expect(e).to.not.be.undefined;
module.exports.shouldBe = (expected, actual) => expect(actual).to.eq(expected);
module.exports.shouldNotBe = (expected, actual) =>
expect(actual).to.not.eq(expected);
module.exports.whenReady = () => {
cy.wait(5000);
return cy.get('#loaded').then(() => cy.window());
};
module.exports.whenReady = () =>
cy.get('#loaded', { timeout: 5000 }).then(() => cy.window());
Loading