- Notifications
You must be signed in to change notification settings - Fork2
A browser JWT as a "session" with expiration observer and server-side validation, zero dependencies.
License
videsk/jwt-webauth
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
A Javascript frontend authorization tokens handler that works with JWT to check expiration and token transactions with the server.
Handle authorization tokens as sessions, based onaccessToken
andrefreshToken
, that will save it in local or session storage, and create an automatic renew when tokens expire and can integrate with request interceptors.
BREAK CHANGE!We release new version with the name jwt-webauth, previous version is deprecated.
- Automatic save tokens in session or local storage
- Automatic storage for remember a session or not
- Expiration observer
- Server-side validation
- Automatically and manually renew the access token with the refresh token
- Events for expiration, renewed, empty and errors
- Compatibility with native fetch API or any HTTP library
From NPM
npm i @videsk/jwt-webauth
Self-hosted
<script src="/dist/jwt-webauth.min.js"></script>
For start, you need instanceWebAuth
.
constauth=newWebAuth(options);
The class receive one argument asobject
. That object contains the following keys:
const{ keys, events, attempts, delay}=options;
keys (optional)
This key, have the "key name" that will store in local or session storage. By default, areauth-key
andauth-key-refresh
, for access and refresh token respectively.
constkeys={accessToken:'auth-key',refreshToken:'auth-key-refresh'};
events (optional)
Set event callbacks byobject
attempts (optional)
Number of attempts before throw error.
delay
Minutes to subtract to JWT expiration to consider is expired. Example: 5 min before expire to force renew.
// Set empty, auto handle existing saved tokensauth.set();// Set with accessToken onlyauth.set(accessToken);// Set with accessToken and refreshTokenauth.set(accessToken,refreshToken);// Also can set if you want "remember session"auth.set(accessToken,refreshToken,true);
This automatically start to observe the expiration of access and/or refresh token. Also check validity of access token by the server and when expire automatically will try to get a new one, only if you set a refresh token.
This property allows you to force renew the access token with the refresh token, so this is relevant when you integrate with interceptors. In case a request returns401 Unauthorized
(typically token expire or blacklisted) you can force renew.
auth.renew();
This is very useful not only when user do a request, seconds before the observer can check that access token was expired, also when access and/or refresh token was invalidated by the server in a blacklist by security reasons (ex. password reset).
So, is important use it directly in your interceptors when you know that access token was expired, blacklisted or invalidated by the server.
WebAuth require as mandatory a few events forverify
andrenew
access token.
The mandatory event isverify
to check server-side validation. If is not present will throw an error.
In case you can to use refresh token needs to set therenew
event. Otherwise, if refresh token is present will throw an error.
Read more about server-side validation in the next section.
The other available events are:
constevents={expired:()=>{},error:()=>{},renewed:()=>{},empty:()=>{},ready:()=>{},};
To set them, you can do it with this elegant way:
auth.on('name-event',callback);// Exampleauth.on('expired',function(){// Do something});// Or less elegantauth.events.expired=()=>{// Do something};
Remember that both method will override the default empty function. So, define a callback per event only one time on your code.
In case ofexpired
event, returns the name of token was expired that will beaccessToken
orrefreshToken
. So, you can difference like this:
auth.on('expired',function(tokenName){if(tokenName==='accessToken')return;// Set function when not use refreshToken// Is refreshTokenlogoutUser();});
Theready
events is useful to set in the base of HTML or template app to know when the accessToken is valid or was renewed. Example:
auth.on('ready',function(){// The accessToken and/or refreshToken are valid// Or accessToken is expired, WebAuth will try to renew, then if the renovation is successful the event will be triggered});
So, is recommended to add theready
event to the base of the app. With that, you can ensure thatready
event will be triggered only if accessToken and/or refreshToken are being valid. Inclusive if was valid from the first time the app was loaded or need to be renewed. Both cases ensure that the app can load with valid accessToken.
This two properties allows you toclean
tokens from storage andlogout
the observer. Thelogout
also clean the tokens, so use stop when you want to reactivate observer manually with.set()
.
// Only clean tokensauth.clean();// Stop all and clean tokensauth.logout();
We recommend to use.logout()
when the user logout from the web app.
When you startWebAuth
, will try to check validity executingverify
event, in case the event return false will be considered as expired otherwise is valid.WebAuth
will try to get a new access token, executing therenew
event only if refresh token is present.
Ifrenew
throw an error,WebAuth
will try the number of attempts to set onoptions
, which by default is 3.
constauth=newWebAuth();auth.on('verify',async()=>{constresponse=awaitfetch('.../verify');constoutput=awaitresponse.json();returnoutput.isValid;});auth.on('renew',async()=>{constresponse=awaitfetch('.../renew');constoutput=awaitresponse.json();returnoutput.accessToken;});
In case exceed the attempts, the event error will throw, and the tokens will remove from the session or local storage. That behavior is by security reasons, to avoid store tokens without server validation.
This is really helpful when user lose connection, also in that cases you can complement with manually Internet connection check, so you can calllogout()
method to avoidWebAuth
remove tokens.
This is the lifecycle ofWebAuth
, when use accessToken and refreshToken.
Instance WebAuth ↓set(accessToken, refreshToken) → observer start → (if empty, no tokens) → fireempty() ↓ fire verify event ↓ (accessToken expire) → fire expire('accessToken') ↓ fire renew event ⇿ (if fails) ← try renew xtimes → fire error(error) ↓ save tokens → observer start → firerenewed() ↓ refreshToken expire ↓fire expired('refreshToken') ↓ end (here request login) → firelogout event
If you don't use a refreshToken, the lifecycle will be like this:
Instance WebAuth ↓ fire verify event ↓set(accessToken, refreshToken) → observer start → (if empty, no tokens) → fireempty() ↓(accessToken expire) → fire expire('accessToken') ↓ end → firelogout evet
We recommend to use eventerror
to check all issues with server side validations. This library was tested so should not throw unhandled errors related to observer.
// Development environmentauth.on('error',function(error){debugger;console.log(error);});// Productionauth.on('error',function(error){// Here can integrate with error monitoring like Sentry});
We strongly recommend useerror
event with error monitoring like Sentry, Bugsnag, LogRocket, etc. The cases when error event should be fired are a malformed JWT and server error response.
This library was tested withMocha
,chai
andchai-http
. Also was created a polyfill ofwindow
to test withlocalStorage
andsessionStorage
in Node,check here.
For coverage was usednyc
.
This library was developed byVidesk with ♥ license LGPL-2.1.
About
A browser JWT as a "session" with expiration observer and server-side validation, zero dependencies.