Skip to content

Commit

Permalink
Merge 1.7.0 beta branch (#419)
Browse files Browse the repository at this point in the history
* Export types from global TypeScript file.

* Fix BaseLoginOptions JSDoc.

* Fix Auth0Client export and integration tests.

* Prevent breaking changes with type and import.

* Add export for Auth0Client type.

* [SDK-1178] Local Storage caching mechanism (#303)

* Refactored existing cache

* Renamed to InMemoryCache
* Removed default export
* Added ICache
* Refactored tests
* Auth0Client now uses ICache instead of implemented cache type

* Added ability to configure cache strategy

* Added VS Code debug configuration for running tests

* Implemented local storage cache

* Made use of "in" to check presence of key in object

* Refactored playground page to use Vue + Bootstrap

* Added ability to clear the token cache

Added clear() to the ICache interface, meaning that this had to be
applied to the memory and localstorage caches.

Made use of jest-localstorage-mock package for easier testing with
localstorage, making the clear method easier to test for the
LocalStorageCache implementation.

* Revamped the playground page with Vue and Bootstrap additions

* Vulnerable dependency update

* Added a section in the readme about the caching strategy

* Fixed integration tests

* Readme wording

* Refactored how items are cleared from local storage

* Refactored cache key

* Readme tweak to make what 'data' is more clear

* Renamed cacheStrategy option to cacheLocation

* Cache now includes client_id in key

* [SDK-1179] Support for rotating refresh tokens (#315)

* Refactored getting token using iframe into its own method

* Implemented getTokenUsingRefreshToken

* Fixed up the playground page to support refresh tokens

* Set offline_access scope during initialization

* Added error condition for when a refresh token isn't stored or no cache exists

* Removed specification of audience when calling token endpoint

* Clarified docs on useRefreshTokens

* Simplified usage of getUniqueScopes in index.ts

* Fixed some playground syntax issues for IE11

* Playground now shows auth info on load if authenticated

* Simplified integration tests

* Added more integration tests around getting access tokens

* Encoded the nonce value when building authorize URLs

* Renamed encodeState to encode

* Fixed broken integration test

* Release 1.7.0-beta.1 (#327)

* Release 1.7.0-beta.1

* Tweaked intermittently-failing test

* Fixed issue with cache not retaining refresh token (#333)

* Fixed issue with cache not retaining refresh token

* Fix integration tests

* Removed unused core-js import

* Extracted 1 day in seconds value to a constant

* Applied comment to be consistant with related test

* Applied brace styling for consistancy

* Reworked expiry tests to mock date instead of using negative exp

* Added some comments to the cache tests to explain the test scenario

* Cleaned up JS return statement styling

* Prepare 1.7.0-beta.2 (#334)

* Wrapped InMemoryCache implementation in a closure (#337)

* Reinstated lock on getTokenSilently

* Fixed up code + tests after rebase

* Fixed up types

* Removed undesirables from the docs generation

* [SDK-1352] Removed setTimeout cache removal in favour of removal-on-read (#354)

* Removed setTimeout cache expiry in favour of expiry-on-read

* Replace magic values with a constant

* [SDK-1279] getTokenSilently retry logic (#336)

* Added retry logic to getJSON

* Moved retry count to a constant

* Reverted changes to oauthToken

* Reduced retry count to 3

* Implemented a timeout around the fetch call

* Made the fetch timeout a default value and adjusted tests

* Fixed broken test after merge

* Implemented AbortController to abort fetch on timeout

* Added abortcontroller polyfill

* Created factory function for AbortController to be mocked and tested

* [SDK-1352] Stop checking `isAuthenticated` cookie on initialization when using local storage (#352)

* Changes to the initialization strategy

* Removed unused import from a test

* Release 1.7.0-beta.3 (#358)

* Fix error in library type definitions (#367)

`// @ts-ignore` comment is not preserved in the generated type definition, which means that library ships broken type definitions and consumers will get an error when they attempt to use it.

Reproduction:

```
$ npm i @auth0/auth0-spa-js@1.7.0-beta.3 typescript
$ cat index.ts
import c from '@auth0/auth0-spa-js';
$ ./node_modules/.bin/tsc --noEmit index.ts
node_modules/@auth0/auth0-spa-js/dist/typings/index.d.ts:9:8 - error TS2440: Import declaration conflicts with local declaration of 'Auth0Client'.

9 import Auth0Client from './Auth0Client';
         ~~~~~~~~~~~

Found 1 error.
```

* [SDK-1386] Fall back to iframe method if no refresh token is available (#364)

* Logic falls back to the iframe method when no refresh token is found

* Cleaned up a variable name

* Updated integration test

* Release 1.7.0-beta.4 (#370)

* Updated cache configuration instructions in the readme

* Removed unused cacheStrategy param from buildAuthorizeUrl

* [SDK-1379] Export constructor (#385)

Export constructor

* Release 1.7.0-beta.5 (#393)

* [SDK-1507] Dependency upgrade (#405)

* Ran npm audit fix

* Updated packages within semver

* Updated typedoc

* Updated rollup to 2.3.3 + plugins

* Updated idtoken-verifier to 2.0.2

* Fixed warnings on async describe blocks

* Updated prettier/pretty-quick

* Updated Husky and ran husky-upgrade

* Updated Cypress, wait-on and concurrently

* Upgraded tslint

* Updated circle image

* [SDK-1516] Web Workers  (#409)

* fetch in a web worker

* token worker

* known issue: doesn't work if user already logged in (need authorization_code grant_type to populate the refresh token)

* add iframe fallback

* fix tests

* We want to load:
`rollup-plugin-worker-loader::module:./token.worker.ts`
But not:
rollup-plugin-worker-loader::module:/Users/adammcgrath/dev/auth0-spa-js/src/token.worker.ts
TODO: check windows

* Fixed ES5 transpilation for rollup worker plugin

* Make messages serializable using `JSON.parse(JSON.stringify({}))`
Swap imports per https://github.com/mo/abortcontroller-polyfill/blob/3f1c13d2e4087ee15ded81786f1110ae547931bb/README.md#using-it-on-internet-explorer-11-msie11

* only use worker for non ie, local refresh token opts

TODO: fix tests

* Fix tests

* Removed refresh token from worker memory when not included in response

* Moved offline_access scope configuration to constructor

* Modified playground to use both factory func and constructor

* Remove Object.assign

* Remove checks to fix rebuild issue

* Abort timed out requests in the Web Worker

* Errors

* Fix tests

* Add some more tests

* DRY up the tests a little

* Moar tests

* unused import

* update rollup-plugin-web-worker-loader
don't run `addEventListener` in tests
add test for missing refresh token and localstorage

* add timeout tests

* add browser tests

* Only include files in the typings copy process

* Fix fallback logic when no RT and no worker

* add browser tests and comments

* bump node version in Jenkinsfile

* Removed unused import

* Added sanity check for web worker support

* Fixed tests for window.Worker check

* Moved constructor tests into Auth0Client

Co-authored-by: Steve Hobbs <steve.hobbs.mail@gmail.com>

* Updated readme with info on refresh tokens (#415)

* Implemented fallback to iframe when given specific audience (#414)

* Check if iframe is still in body before removing (#399)

If the iframe is removed from the DOM prior to the timeout it would error on removeChild.

Error thrown: `Uncaught DOMException: Failed to execute 'removeChild' on 'Node': The node to be removed is not a child of this node.`

Bug introduced in #376

Co-authored-by: Steve Hobbs <steve.hobbs@auth0.com>

* Check if source of event exists before closing it (#410)

When the iframe is closed, the source of the event message is null, resulting in an error: Cannot read property 'close' of undefined (Chrome).

Co-authored-by: Steve Hobbs <steve.hobbs@auth0.com>

* Removed unused error import

Co-authored-by: maxswa <mkswartwout@gmail.com>
Co-authored-by: Yaroslav Admin <devoto13@gmail.com>
Co-authored-by: Adam Mcgrath <adam.mcgrath@auth0.com>
Co-authored-by: Paul Falgout <paul@otterball.com>
Co-authored-by: gerritdeperrit <gertjansterrenburg@gmail.com>
  • Loading branch information
6 people authored Apr 15, 2020
1 parent 2503c0f commit 476caea
Show file tree
Hide file tree
Showing 54 changed files with 35,410 additions and 26,814 deletions.
2 changes: 1 addition & 1 deletion .circleci/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ version: 2
jobs:
build:
docker:
- image: cypress/browsers:chrome67
- image: cypress/browsers:node12.13.0-chrome80-ff74
working_directory: ~/repo
steps:
- checkout
Expand Down
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@ coverage
stats.html
cypress/screenshots
cypress/videos
.release
.release
.idea
36 changes: 36 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Jest (current file)",
"program": "${workspaceFolder}/node_modules/.bin/jest",
"args": ["${fileBasenameNoExtension}"],
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"disableOptimisticBPs": true
},
{
"type": "node",
"request": "launch",
"name": "Jest (all tests)",
"program": "${workspaceFolder}/node_modules/.bin/jest",
"args": ["--runInBand"],
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"disableOptimisticBPs": true
},
{
"type": "node",
"request": "launch",
"name": "Build",
"program": "${workspaceFolder}/node_modules/.bin/rollup",
"args": ["-m", "-c"],
"console": "integratedTerminal"
}
]
}
49 changes: 49 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,54 @@
# Change Log

## [v1.7.0-beta.5](https://github.com/auth0/auth0-spa-js/tree/v1.7.0-beta.5) (2020-03-26)

[Full Changelog](https://github.com/auth0/auth0-spa-js/compare/v1.7.0-beta.4...v1.7.0-beta.5)

**Changed**

- [SDK-1379] Export constructor [\#385](https://github.com/auth0/auth0-spa-js/pull/385) ([adamjmcgrath](https://github.com/adamjmcgrath))

## [v1.7.0-beta.4](https://github.com/auth0/auth0-spa-js/tree/v1.7.0-beta.4) (2020-03-03)

[Full Changelog](https://github.com/auth0/auth0-spa-js/compare/v1.7.0-beta.3...v1.7.0-beta.4)

**Changed**

- [SDK-1386] Fall back to iframe method if no refresh token is available [\#364](https://github.com/auth0/auth0-spa-js/pull/364) ([stevehobbsdev](https://github.com/stevehobbsdev))

**Fixed**

- Fix error in library type definitions [\#367](https://github.com/auth0/auth0-spa-js/pull/367) ([devoto13](https://github.com/devoto13))

## [v1.7.0-beta.3](https://github.com/auth0/auth0-spa-js/tree/v1.7.0-beta.3) (2020-02-17)

[Full Changelog](https://github.com/auth0/auth0-spa-js/compare/v1.7.0-beta.2...v1.7.0-beta.3)

**Added**

- Export types from global TypeScript file. [\#310](https://github.com/auth0/auth0-spa-js/pull/310) ([maxswa](https://github.com/maxswa))

**Changed**

- [SDK-1352] Removed setTimeout cache removal in favour of removal-on-read [\#354](https://github.com/auth0/auth0-spa-js/pull/354) ([stevehobbsdev](https://github.com/stevehobbsdev))
- [SDK-1352] Stop checking `isAuthenticated` cookie on initialization when using local storage [\#352](https://github.com/auth0/auth0-spa-js/pull/352) ([stevehobbsdev](https://github.com/stevehobbsdev))
- [SDK-1279] getTokenSilently retry logic [\#336](https://github.com/auth0/auth0-spa-js/pull/336) ([stevehobbsdev](https://github.com/stevehobbsdev))

## [v1.7.0-beta.2](https://github.com/auth0/auth0-spa-js/tree/v1.7.0-beta.2) (2020-01-16)

[Full Changelog](https://github.com/auth0/auth0-spa-js/compare/v1.7.0-beta.1...v1.7.0-beta.2)

**Changed**

- Fixed issue with cache not retaining refresh token [\#333](https://github.com/auth0/auth0-spa-js/pull/333) ([stevehobbsdev](https://github.com/stevehobbsdev))

## [v1.7.0-beta.1](https://github.com/auth0/auth0-spa-js/tree/v1.7.0-beta.1) (2020-01-08)

**Added**

- Ability to use either an in-memory cache (the default) or localstorage to store tokens - [stevehobbsdev](https://github.com/stevehobbsdev) - https://github.com/auth0/auth0-spa-js/pull/303
- Added support for rotating refresh tokens - [stevehobbsdev](https://github.com/stevehobbsdev) - https://github.com/auth0/auth0-spa-js/pull/315

## [v1.6.5](https://github.com/auth0/auth0-spa-js/tree/v1.6.5) (2020-03-19)

[Full Changelog](https://github.com/auth0/auth0-spa-js/compare/v1.6.4...v1.6.5)
Expand Down
12 changes: 6 additions & 6 deletions Jenkinsfile
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@ pipeline {
agent {
label 'crew-brucke'
}

tools {
nodejs '10.15.1'
nodejs '12.9.1'
}

options {
timeout(time: 10, unit: 'MINUTES')
}

stages {
stage('SharedLibs') {
steps {
Expand Down Expand Up @@ -52,10 +52,10 @@ pipeline {
}
}
}

post {
cleanup {
deleteDir()
}
}
}
}
80 changes: 67 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ Auth0 SDK for Single Page Applications using [Authorization Code Grant Flow with
From the CDN:

```html
<script src="https://cdn.auth0.com/js/auth0-spa-js/1.6/auth0-spa-js.production.js"></script>
<script src="https://cdn.auth0.com/js/auth0-spa-js/1.7/auth0-spa-js.production.js"></script>
```

Using [npm](https://npmjs.org):
Expand Down Expand Up @@ -56,17 +56,35 @@ 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) => {
//...
});

//or, you can just instantiate the client on it's own
import { Auth0Client } from '@auth0/auth0-spa-js';

const auth0 = new Auth0Client({
domain: '<AUTH0_DOMAIN>',
client_id: '<AUTH0_CLIENT_ID>',
redirect_uri: '<MY_CALLBACK_URL>',
});

//if you do this, you'll need to check the session yourself
try {
await getTokenSilently();
} catch (error) {
if (error.error !== 'login_required') {
throw error;
}
}
```

### 1 - Login
Expand Down Expand Up @@ -102,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 @@ -124,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 @@ -135,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 All @@ -164,6 +182,42 @@ document.getElementById('logout').addEventListener('click', () => {
});
```

### Data caching options

The SDK can be configured to cache ID tokens and access tokens either in memory or in local storage. The default is in memory. This setting can be controlled using the `cacheLocation` option when creating the Auth0 client.

To use the in-memory mode, no additional options need are required as this is the default setting. To configure the SDK to cache data using local storage, set `cacheLocation` as follows:

```js
await createAuth0Client({
domain: '<AUTH0_DOMAIN>',
client_id: '<AUTH0_CLIENT_ID>',
redirect_uri: '<MY_CALLBACK_URL>',
cacheLocation: 'localstorage', // valid values are: 'memory' or 'localstorage'
});
```

**Important:** This feature will allow the caching of data **such as ID and access tokens** to be stored in local storage. Exercising this option changes the security characteristics of your application and **should not be used lightly**. Extra care should be taken to mitigate against XSS attacks and minimize the risk of tokens being stolen from local storage.

### Refresh Tokens

Refresh tokens can be used to request new access tokens. [Read more about how our refresh tokens work for browser-based applications](https://auth0.com/docs/tokens/concepts/refresh-token-rotation) to help you decide whether or not you need to use them.

To enable the use of refresh tokens, set the `useRefreshTokens` option to `true`:

```js
await createAuth0Client({
domain: '<AUTH0_DOMAIN>',
client_id: '<AUTH0_CLIENT_ID>',
redirect_uri: '<MY_CALLBACK_URL>',
useRefreshTokens: true,
});
```

Using this setting will cause the SDK to automatically send the `offline_access` scope to the authorization server. Refresh tokens will then be used to exchange for new access tokens instead of using a hidden iframe, and calls the `/oauth/token` endpoint directly. This means that the SDK does not rely on third-party cookies when using refresh tokens.

**Note** This configuration option requires Rotating Refresh Tokens to be [enabled for your Auth0 Tenant](https://auth0.com/docs/tokens/guides/configure-refresh-token-rotation).

## Contributing

We appreciate feedback and contribution to this repo! Before you get started, please see the following:
Expand Down
Loading

0 comments on commit 476caea

Please sign in to comment.