- Notifications
You must be signed in to change notification settings - Fork295
A simple Node.js client library for Oauth2
lelylan/simple-oauth2
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Simple OAuth2 is a Node.js client library for theOAuth 2.0 authorization framework.OAuth 2.0 is the industry-standard protocol for authorization, enabling third-party applications to obtain limited access to an HTTP service, either on behalf of a resource owner or by allowing the third-party application to obtain access on its own behalf.
Version | Node support |
---|---|
5.x | Node 14.x or higher |
6.x (Development) | Node 16.x or higher |
Older node versions are unsupported.
Install the client library usingnpm:
npm install --save simple-oauth2
With a minimal configuration, create a client instance of any supportedgrant type.
constconfig={client:{id:'<client-id>',secret:'<client-secret>'},auth:{tokenHost:'https://api.oauth.com'}};const{ ClientCredentials, ResourceOwnerPassword, AuthorizationCode}=require('simple-oauth2');
For a complete reference of configuration options, see theAPI Options
Depending on your use-case, any of the following supported grant types may be useful:
TheAuthorization Code grant type is used by confidential and public clients to exchange an authorization code for an access token. After the user returns to the client via the redirect URL, the application will get the authorization code from the URL and use it to request an access token.
asyncfunctionrun(){constclient=newAuthorizationCode(config);constauthorizationUri=client.authorizeURL({redirect_uri:'http://localhost:3000/callback',scope:'<scope>',state:'<state>',customParam:'foo',// non-standard oauth params may be passed as well});// Redirect example using Express (see http://expressjs.com/api.html#res.redirect)res.redirect(authorizationUri);consttokenParams={code:'<code>',redirect_uri:'http://localhost:3000/callback',scope:'<scope>',};try{constaccessToken=awaitclient.getToken(tokenParams);}catch(error){console.log('Access Token Error',error.message);}}run();
See theAPI reference for a complete reference of available options or any of our available examples at theexample folder.
TheResource Owner Password Credentials grant type is a way to exchange a user's credentials for an access token. Because the client application has to collect the user's password and send it to the authorization server, it is not recommended that this grant be used at all anymore.
asyncfunctionrun(){constclient=newResourceOwnerPassword(config);consttokenParams={username:'username',password:'password',scope:'<scope>',};try{constaccessToken=awaitclient.getToken(tokenParams);}catch(error){console.log('Access Token Error',error.message);}}run();
See theAPI reference for a complete reference of available options.
TheClient Credentials grant type is used by clients to obtain an access token outside of the context of a user. This is typically used by clients to access resources about themselves rather than to access a user's resources.
asyncfunctionrun(){constclient=newClientCredentials(config);consttokenParams={scope:'<scope>',};try{constaccessToken=awaitclient.getToken(tokenParams);}catch(error){console.log('Access Token error',error.message);}}run();
See theAPI reference for a complete reference of available options.
On completion of anysupported grant type, an access token will be obtained. A list of supported operations can be found below.
On long-lived applications, it is often necessary to refresh access tokens. In such scenarios, the access token is usually persisted in an external database by first serializing it.
asyncfunctionrun(){constaccessTokenJSONString=JSON.stringify(accessToken);awaitpersistAccessTokenJSON(accessTokenJSONString);}run();
By the time we need to refresh the persistent access token, we can get back anAccessToken instance by using the client's.createToken method.
asyncfunctionrun(){constaccessTokenJSONString=awaitgetPersistedAccessTokenJSON();letaccessToken=client.createToken(JSON.parse(accessTokenJSONString));}run();
Once we have determined the access token needs refreshing with the.expired() method, we can finally refresh it with a.refresh() method call.
asyncfunctionrun(){if(accessToken.expired()){try{constrefreshParams={scope:'<scope>',};accessToken=awaitaccessToken.refresh(refreshParams);}catch(error){console.log('Error refreshing access token: ',error.message);}}}run();
The.expired() helper is useful for knowing when a token has definitively expired. However, there is a common race condition when tokens are near expiring. If an OAuth 2.0 token is issued with aexpires_in
property (as opposed to anexpires_at
property), there can be discrepancies between the time the OAuth 2.0 server issues the access token and when it is received.
These come down to factors such as network and processing latency and can be worked around by preemptively refreshing the access token:
asyncfunctionrun(){constEXPIRATION_WINDOW_IN_SECONDS=300;// Window of time before the actual expiration to refresh the tokenif(accessToken.expired(EXPIRATION_WINDOW_IN_SECONDS)){try{accessToken=awaitaccessToken.refresh();}catch(error){console.log('Error refreshing access token: ',error.message);}}}run();
Warning: Tokens obtained with the Client Credentials grant may not be refreshed. Fetch a new token when it's expired.
See theAPI reference for a complete reference of available options.
When you've done with the token or you want to log out, you can revoke both access and refresh tokens.
asyncfunctionrun(){try{awaitaccessToken.revoke('access_token');awaitaccessToken.revoke('refresh_token');}catch(error){console.log('Error revoking token: ',error.message);}}run();
As a convenience method, you can also revoke both tokens in a single call:
asyncfunctionrun(){try{// Revokes both tokens, refresh token is only revoked if the access_token is properly revokedawaitaccessToken.revokeAll();}catch(error){console.log('Error revoking token: ',error.message);}}run();
See theAPI reference for a complete reference of available options.
Whenever a client or server error is produced, aboom error is thrown by the library. As such anyboom error property is available, but the exact information may vary according to the type of error.
asyncfunctionrun(){constclient=newClientCredentials(config);try{awaitclient.getToken();}catch(error){console.log(error.output);}}run();// { statusCode: 401,// payload:// { statusCode: 401,// error: 'Unauthorized',// message: 'Response Error: 401 Unauthorized'},// headers: {}}
This module uses thedebug module to help on error diagnosis. Use the following environment variable to help in your debug journey:
DEBUG=*simple-oauth2*
SeeCONTRIBUTING
Special thanks to the following people for submitting patches.
SeeCHANGELOG
Simple OAuth 2.0 is licensed under theApache License, Version 2.0
Simple OAuth 2.0 come to life thanks to the work I've made in Lelylan, an open source microservices architecture for the Internet of Things. If this project helped you in any way, think about giving us astar on GitHub.

About
A simple Node.js client library for Oauth2
Resources
Uh oh!
There was an error while loading.Please reload this page.