OAuth2 Service Worker handler
When it comes to saving credentials in the browser, HttpOnly Cookies are often the preferred method as they are not vulnerable to cross-site scripting (XSS) attacks. However, when using Single Sign-On (SSO), the credentials are usually provided in the form of tokens that are intended to be sent via the Authorization header.
While it may be tempting to simply store these tokens in the browser's localStorage, this can introduce security risks if any third-party code is present or if a user is able to add custom JavaScript to the application. Storing the tokens in regular Cookies may also not be the best solution as it defeats the purpose of using Cookies in the first place.
This library is an implementation of the OAuth2 recommendations for Single Page Applications that uses a Service Worker to store the tokens in SW cache, which is inaccessable to the main app.
npm install auth-worker
Note: This example shows usage with Google, but the lib supports multiple providers out of the box and custom providers can also be defined.
// service-worker.ts
import { initAuthServiceWorker } from 'auth-worker/worker';
import { google } from 'auth-worker/providers';
initAuthServiceWorker({ google }, '/auth', ['/allowed', '/routes']);
Name | Type | Description |
---|---|---|
providers |
Record<string, IProvider> |
The providers that should be used. |
path |
string |
The path that will be used for the auth endpoints. This should be a path that isn't used for anythin else, so altrough /auth might be the obvious choice, you might need to use something else in your app. |
allowlist |
Array<RegExp | string | { url: RegExp | string; methods: Array<'GET' | 'POST' | 'PATCH' | 'PUT' | 'HEAD' | 'DELETE'> }> |
The allowlist of URLs. Everything is allowed if the array is not passed. |
secret |
string? |
The secret that will be used as an base for the storage encription. If not set, nothing will be persisted and the login will only work while the service worker is active (in-memory storage). This is the only secure option. If you want better UX and can afford a bit weaker security (basically, security trough obscurity), you can define a secret key here that will be used to encrypt data when writing it to IndexedDB |
// index.ts
import { loadAuthServiceWorker } from 'auth-worker';
loadAuthServiceWorker({
google: {
clientId: 'example-client-id',
scopes: 'https://www.googleapis.com/auth/userinfo.profile',
},
}).catch(console.error);
Name | Type | Description |
---|---|---|
config |
IConfig |
The providers that should be used. |
options.workerPath? |
string |
The location of the service worker. Defaults to "./service-worker.js" |
options.scope? |
string |
The scope opf the service worker. Defaults to "/" |
options.debug? |
boolean |
Whether to enable debug mode. Defaults to false |
Note: The examples here are using the /auth
prefix, but this can be changed in the initAuthServiceWorker
function.
- To log in, use the link in format
/auth/login/{provider}
. For example,/auth/login/google
. After the successful login, the user will be redirected to/
. - To log out, use the
/auth/logout
link. After the successful logout, the user will be redirected to/
. - To get the user info, use the
getUserInfo
function. For example:
import { getUserInfo } from 'auth-worker';
const userInfo = await getUserInfo();
- To make an authenticated API call, make sure the wanted API endpoint is allowed in the
initAuthServiceWorker
function and add theX-Use-Auth
header to the request. For example:
const response = await fetch('https://example.com/api', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Use-Auth': 'true',
},
body: JSON.stringify({
foo: 'bar',
}),
});
By default, this library will not persist the tokens in the browser. Instead, it will just keep them in memory while the service worker is active. This is the most secure option, but it also means that the user will be logged out when the service worker is terminated (for example, when the browser is closed).
If you want to persist the tokens, you can pass a secret key to the initAuthServiceWorker
function. This will enable the storage in IndexedDB, but it will also mean that the tokens will be stored in the browser and it will be accessible to any script that is able to run in the context of your app. This is a bit safer than just keeping it in plaintext, since the encryption key is hardcoded in the service worker and is not accessible to the main app, but it is still not as secure as the in-memory storage because the key can be extracted (e.g., manually by reading the source code of the page).
Published under the MIT License.
Maintained and sponsored by Infinum.