Skip to content

Commit

Permalink
[SDK-1417] Customizable default scopes (#435)
Browse files Browse the repository at this point in the history
* Extracted changes needed to customize defaultScope

* Moved existing defaultScopes test to the right place

* getUniqueScopes moved into scope.ts

* Refactor getUniqueScopes into its own module

This allows it to me mocked or unmocked separately from utils.
index.test.ts has been completely refactored to use an unmocked version
and the expectations have changed as a result.

* Stop mutating optios.scope and store in separate var

* Added tests for relevant functions for using advanced default scopes

* Fix constructor after merge

* advancedOptions.defaultScope can accept empty/null value

* Added advanced section to readme

Docs build to follow in the release PR

* Set up proper spy for getUniqueScopes

* Fixed types in JS docs

* Simplified getUniqueScopes implementation

* Cleaned up index test file

* Simplified the defaultScope check using null chaining operator

Co-authored-by: Sri Hari Raju Penmatsa <pshraju@gmail.com>
  • Loading branch information
Steve Hobbs and srihari93 committed Apr 30, 2020
1 parent 0fc02ad commit 0af848a
Show file tree
Hide file tree
Showing 10 changed files with 365 additions and 231 deletions.
44 changes: 29 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -56,15 +56,15 @@ import createAuth0Client from '@auth0/auth0-spa-js';
const auth0 = await createAuth0Client({
domain: '<AUTH0_DOMAIN>',
client_id: '<AUTH0_CLIENT_ID>',
redirect_uri: '<MY_CALLBACK_URL>',
redirect_uri: '<MY_CALLBACK_URL>'
});

//with promises
createAuth0Client({
domain: '<AUTH0_DOMAIN>',
client_id: '<AUTH0_CLIENT_ID>',
redirect_uri: '<MY_CALLBACK_URL>',
}).then((auth0) => {
redirect_uri: '<MY_CALLBACK_URL>'
}).then(auth0 => {
//...
});

Expand All @@ -74,7 +74,7 @@ import { Auth0Client } from '@auth0/auth0-spa-js';
const auth0 = new Auth0Client({
domain: '<AUTH0_DOMAIN>',
client_id: '<AUTH0_CLIENT_ID>',
redirect_uri: '<MY_CALLBACK_URL>',
redirect_uri: '<MY_CALLBACK_URL>'
});

//if you do this, you'll need to check the session yourself
Expand Down Expand Up @@ -120,9 +120,9 @@ document.getElementById('login').addEventListener('click', () => {

//in your callback route (<MY_CALLBACK_URL>)
window.addEventListener('load', () => {
auth0.handleRedirectCallback().then((redirectResult) => {
auth0.handleRedirectCallback().then(redirectResult => {
//logged in. you can get the user profile like this:
auth0.getUser().then((user) => {
auth0.getUser().then(user => {
console.log(user);
});
});
Expand All @@ -142,8 +142,8 @@ document.getElementById('call-api').addEventListener('click', async () => {
const result = await fetch('https://myapi.com', {
method: 'GET',
headers: {
Authorization: `Bearer ${accessToken}`,
},
Authorization: `Bearer ${accessToken}`
}
});
const data = await result.json();
console.log(data);
Expand All @@ -153,16 +153,16 @@ document.getElementById('call-api').addEventListener('click', async () => {
document.getElementById('call-api').addEventListener('click', () => {
auth0
.getTokenSilently()
.then((accessToken) =>
.then(accessToken =>
fetch('https://myapi.com', {
method: 'GET',
headers: {
Authorization: `Bearer ${accessToken}`,
},
Authorization: `Bearer ${accessToken}`
}
})
)
.then((result) => result.json())
.then((data) => {
.then(result => result.json())
.then(data => {
console.log(data);
});
});
Expand Down Expand Up @@ -193,7 +193,7 @@ await createAuth0Client({
domain: '<AUTH0_DOMAIN>',
client_id: '<AUTH0_CLIENT_ID>',
redirect_uri: '<MY_CALLBACK_URL>',
cacheLocation: 'localstorage', // valid values are: 'memory' or 'localstorage'
cacheLocation: 'localstorage' // valid values are: 'memory' or 'localstorage'
});
```

Expand All @@ -210,7 +210,7 @@ await createAuth0Client({
domain: '<AUTH0_DOMAIN>',
client_id: '<AUTH0_CLIENT_ID>',
redirect_uri: '<MY_CALLBACK_URL>',
useRefreshTokens: true,
useRefreshTokens: true
});
```

Expand All @@ -226,6 +226,20 @@ If the fallback mechanism fails, a `login_required` error will be thrown and cou

**Note**: This fallback mechanism does still require access to the Auth0 session cookie, so if third-party cookies are being blocked then this fallback will not work and the user must re-authenticate in order to get a new refresh token.

### Advanced options

Advanced options can be set by specifying the `advancedOptions` property when configuring `Auth0Client`. Learn about the complete set of advanced options in the [API documentation](https://auth0.github.io/auth0-spa-js/interfaces/advancedoptions.html)

```js
createAuth0Client({
domain: '<AUTH0_DOMAIN>',
client_id: '<AUTH0_CLIENT_ID>',
advancedOptions: {
defaultScope: 'email' // change the scopes that are applied to every authz request. **Note**: `openid` is always specified regardless of this setting
}
});
```

## Contributing

We appreciate feedback and contribution to this repo! Before you get started, please see the following:
Expand Down
80 changes: 60 additions & 20 deletions __tests__/Auth0Client.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import unfetch from 'unfetch';
import { verify } from '../src/jwt';
import { MessageChannel } from 'worker_threads';
import * as utils from '../src/utils';
import { Auth0ClientOptions, IdToken } from '../src';
import * as scope from '../src/scope';

jest.mock('unfetch');
jest.mock('../src/jwt');
Expand Down Expand Up @@ -34,7 +36,10 @@ const fetchResponse = (ok, json) =>
json: () => Promise.resolve(json)
});

const setup: any = (config?, claims?) => {
const setup = (
config?: Partial<Auth0ClientOptions>,
claims?: Partial<IdToken>
) => {
const auth0 = new Auth0Client(
Object.assign(
{
Expand All @@ -45,6 +50,7 @@ const setup: any = (config?, claims?) => {
config
)
);

mockVerify.mockReturnValue({
claims: Object.assign(
{
Expand All @@ -53,6 +59,7 @@ const setup: any = (config?, claims?) => {
claims
)
});

return auth0;
};

Expand Down Expand Up @@ -96,23 +103,40 @@ describe('Auth0Client', () => {
};
mockWindow.MessageChannel = MessageChannel;
mockWindow.Worker = {};
jest.spyOn(utils, 'getUniqueScopes');
jest.spyOn(scope, 'getUniqueScopes');
});

afterEach(() => {
jest.clearAllMocks();
});

it('automatically adds the offline_access scope during construction', async () => {
setup({
it('automatically adds the offline_access scope during construction', () => {
const auth0 = setup({
useRefreshTokens: true,
scope: 'test-scope'
});

expect(utils.getUniqueScopes).toHaveBeenCalledWith(
'test-scope',
'offline_access'
);
expect((<any>auth0).scope).toBe('test-scope offline_access');
});

it('ensures the openid scope is defined when customizing default scopes', () => {
const auth0 = setup({
advancedOptions: {
defaultScope: 'test-scope'
}
});

expect((<any>auth0).defaultScope).toBe('openid test-scope');
});

it('allows an empty custom default scope', () => {
const auth0 = setup({
advancedOptions: {
defaultScope: null
}
});

expect((<any>auth0).defaultScope).toBe('openid');
});

it('should log the user in and get the token', async () => {
Expand Down Expand Up @@ -143,8 +167,11 @@ describe('Auth0Client', () => {
const auth0 = setup({
useRefreshTokens: true
});
expect(auth0.worker).toBeDefined();

expect((<any>auth0).worker).toBeDefined();

await login(auth0);

mockFetch.mockResolvedValueOnce(
fetchResponse(true, {
id_token: 'my_id_token',
Expand All @@ -153,7 +180,9 @@ describe('Auth0Client', () => {
expires_in: 86400
})
);

const access_token = await auth0.getTokenSilently({ ignoreCache: true });

assertPost(
'https://auth0_domain/oauth/token',
{
Expand All @@ -164,6 +193,7 @@ describe('Auth0Client', () => {
},
1
);

expect(access_token).toEqual('my_access_token');
});

Expand All @@ -172,15 +202,19 @@ describe('Auth0Client', () => {
useRefreshTokens: true,
cacheLocation: 'localstorage'
});
expect(auth0.worker).toBeUndefined();

expect((<any>auth0).worker).toBeUndefined();

await login(auth0);

assertPost('https://auth0_domain/oauth/token', {
redirect_uri: 'my_callback_url',
client_id: 'auth0_client_id',
code_verifier: '123',
grant_type: 'authorization_code',
code: 'my_code'
});

mockFetch.mockResolvedValueOnce(
fetchResponse(true, {
id_token: 'my_id_token',
Expand All @@ -189,7 +223,9 @@ describe('Auth0Client', () => {
expires_in: 86400
})
);

const access_token = await auth0.getTokenSilently({ ignoreCache: true });

assertPost(
'https://auth0_domain/oauth/token',
{
Expand All @@ -200,6 +236,7 @@ describe('Auth0Client', () => {
},
1
);

expect(access_token).toEqual('my_access_token');
});

Expand All @@ -211,7 +248,7 @@ describe('Auth0Client', () => {
cacheLocation: 'memory'
});

expect(auth0.worker).toBeUndefined();
expect((<any>auth0).worker).toBeUndefined();

await login(auth0);

Expand Down Expand Up @@ -252,7 +289,8 @@ describe('Auth0Client', () => {
const auth0 = setup({
useRefreshTokens: true
});
expect(auth0.worker).toBeDefined();

expect((<any>auth0).worker).toBeDefined();
await login(auth0);
mockFetch.mockReset();
mockFetch.mockImplementation(() => Promise.reject(new Error('my_error')));
Expand All @@ -266,7 +304,7 @@ describe('Auth0Client', () => {
const auth0 = setup({
useRefreshTokens: true
});
expect(auth0.worker).toBeDefined();
expect((<any>auth0).worker).toBeDefined();
await login(auth0);
mockFetch.mockReset();
mockFetch.mockResolvedValue(
Expand All @@ -290,7 +328,9 @@ describe('Auth0Client', () => {
const auth0 = setup({
useRefreshTokens: true
});
expect(auth0.worker).toBeDefined();

expect((<any>auth0).worker).toBeDefined();

await login(auth0);
mockFetch.mockReset();
mockFetch.mockImplementation(
Expand Down Expand Up @@ -324,7 +364,7 @@ describe('Auth0Client', () => {
const auth0 = setup({
useRefreshTokens: true
});
expect(auth0.worker).toBeDefined();
expect((<any>auth0).worker).toBeDefined();
await login(auth0, true, { refresh_token: '' });
jest.spyOn(<any>utils, 'runIframe').mockResolvedValue({
access_token: 'my_access_token',
Expand All @@ -348,7 +388,7 @@ describe('Auth0Client', () => {
useRefreshTokens: true,
cacheLocation: 'localstorage'
});
expect(auth0.worker).toBeUndefined();
expect((<any>auth0).worker).toBeUndefined();
await login(auth0);
mockFetch.mockReset();
mockFetch.mockImplementation(() => Promise.reject(new Error('my_error')));
Expand All @@ -363,7 +403,7 @@ describe('Auth0Client', () => {
useRefreshTokens: true,
cacheLocation: 'localstorage'
});
expect(auth0.worker).toBeUndefined();
expect((<any>auth0).worker).toBeUndefined();
await login(auth0);
mockFetch.mockReset();
mockFetch.mockResolvedValue(
Expand All @@ -388,7 +428,7 @@ describe('Auth0Client', () => {
useRefreshTokens: true,
cacheLocation: 'localstorage'
});
expect(auth0.worker).toBeUndefined();
expect((<any>auth0).worker).toBeUndefined();
await login(auth0);
mockFetch.mockReset();
mockFetch.mockImplementation(
Expand Down Expand Up @@ -422,7 +462,7 @@ describe('Auth0Client', () => {
useRefreshTokens: true,
cacheLocation: 'localstorage'
});
expect(auth0.worker).toBeUndefined();
expect((<any>auth0).worker).toBeUndefined();
await login(auth0, true, { refresh_token: '' });
jest.spyOn(<any>utils, 'runIframe').mockResolvedValue({
access_token: 'my_access_token',
Expand Down Expand Up @@ -451,7 +491,7 @@ describe('Auth0Client', () => {
const auth0 = setup({
useRefreshTokens: true
});
expect(auth0.worker).toBeUndefined();
expect((<any>auth0).worker).toBeUndefined();
await login(auth0, true, { refresh_token: '' });
jest.spyOn(<any>utils, 'runIframe').mockResolvedValue({
access_token: 'my_access_token',
Expand Down

0 comments on commit 0af848a

Please sign in to comment.