OAuth2Server
Represents an OAuth2 server instance.
constOAuth2Server=require('@node-oauth/oauth2-server');
newOAuth2Server(options)
InstantiatesOAuth2Server using the supplied model.
Arguments:
Name | Type | Description |
|---|---|---|
options | Object | Server options. |
options.model | Object | TheModel. |
Return value:
A newOAuth2Server instance.
Remarks:
Any valid option forOAuth2Server#authenticate(),OAuth2Server#authorize() andOAuth2Server#token() can be passed to the constructor as well. The supplied options will be used as default for the other methods.
Basic usage:
constoauth=newOAuth2Server({model:require('./model')});
Advanced example with additional options:
constoauth=newOAuth2Server({model:require('./model'),allowBearerTokensInQueryString:true,accessTokenLifetime:4*60*60});
authenticate(request,response,[options])
Authenticates a request.
Arguments:
Name | Type | Description |
|---|---|---|
request | Request object. | |
response | Response object. | |
[options={}] | Object | Handler options. |
[options.scope=undefined] | String[] | The scope(s) to authenticate. |
[options.addAcceptedScopesHeader=true] | Boolean | Set the |
[options.addAuthorizedScopesHeader=true] | Boolean | Set the |
[options.allowBearerTokensInQueryString=false] | Boolean | Allow clients to pass bearer tokens in the query string of a request. |
Return value:
APromise that resolves to the access token object returned fromModel#getAccessToken().In case of an error, the promise rejects with one of the error types derived fromOAuthError.
Possible errors include but are not limited to:
- UnauthorizedRequestError:
The protected resource request failed authentication.
Remarks:
constoauth=newOAuth2Server({model:...});functionauthenticateHandler(options){returnfunction(req,res,next){letrequest=newRequest(req);letresponse=newResponse(res);returnoauth.authenticate(request,response,options).then(function(token){res.locals.oauth={token:token};next();}).catch(function(err){// handle error condition});}}
authorize(request,response,[options])
Authorizes a token request.
Arguments:
Name | Type | Description |
|---|---|---|
request | Request object. | |
[request.query.allowed=undefined] | String |
|
response | Response object. | |
[options={}] | Object | Handler options. |
[options.authenticateHandler=undefined] | Object | The authenticate handler (see remarks section). |
[options.allowEmptyState=false] | Boolean | Allow clients to specify an empty |
[options.authorizationCodeLifetime=300] | Number | Lifetime of generated authorization codes in seconds (default = 5 minutes). |
Return value:
APromise that resolves to the authorization code object returned fromModel#saveAuthorizationCode().In case of an error, the promise rejects with one of the error types derived fromOAuthError.
Possible errors include but are not limited to:
- AccessDeniedError
The resource owner denied the access request (i.e.
request.query.allowwas'false').
Remarks:
Ifrequest.query.allowed equals the string'false' the access request is denied and the returned promise is rejected with anAccessDeniedError.
In order to retrieve the user associated with the request,options.authenticateHandler should be supplied.TheauthenticateHandler has to be an object implementing ahandle(request,response) function that returns a user object.If there is no associated user (i.e. the user is not logged in) a falsy value should be returned.
letauthenticateHandler={handle:function(request,response){return/* get authenticated user */;}};
When working with a session-based login mechanism, the handler can simply look like this:
letauthenticateHandler={handle:function(request,response){returnrequest.session.user;}};
Todo
MoveauthenticateHandler to it’s own section.
constoauth=newOAuth2Server({model:...});functionauthorizeHandler(options){returnfunction(req,res,next){letrequest=newRequest(req);letresponse=newResponse(res);returnoauth.authorize(request,response,options).then(function(code){res.locals.oauth={code:code};next();}).catch(function(err){// handle error condition});}}
token(request,response,[options])
Retrieves a new token for an authorized token request.
Arguments:
Name | Type | Description |
|---|---|---|
request | Request object. | |
response | Response object. | |
[options={}] | Object | Handler options. |
[options.accessTokenLifetime=3600] | Number | Lifetime of generated access tokens in seconds (default = 1 hour). |
[options.refreshTokenLifetime=1209600] | Number | Lifetime of generated refresh tokens in seconds (default = 2 weeks). |
[options.allowExtendedTokenAttributes=false] | Boolean | Allow extended attributes to be set on the returned token (see remarks section). |
[options.requireClientAuthentication={}] | Object | Require a client secret (see remarks section). Defaults to |
[options.alwaysIssueNewRefreshToken=true] | Boolean | Always revoke the used refresh token and issue a new one for the |
[options.extendedGrantTypes={}] | Object | Additional supported grant types. |
Return value:
APromise that resolves to the token object returned fromModel#saveToken().In case of an error, the promise rejects with one of the error types derived fromOAuthError.
Possible errors include but are not limited to:
- InvalidGrantError:
The access token request was invalid or not authorized.
Remarks:
Ifoptions.allowExtendedTokenAttributes istrue any additional properties set on the object returned fromModel#saveToken() are copied to the token response sent to the client.
By default all grant types require the client to send it’sclient_secret with the token request.options.requireClientAuthentication can be used to disable this check for selected grants. If used, this server option must be an object containing properties set totrue orfalse. Possible keys for the object include all supported values for the token request’sgrant_type field (authorization_code,client_credentials,password andrefresh_token). Grants that are not specified default totrue which enables verification of theclient_secret.
letoptions={// ...// Allow token requests using the password grant to not include a client_secret.requireClientAuthentication:{password:false}};
options.extendedGrantTypes is an object mapping extension grant URIs to handler types, for example:
letoptions={// ...extendedGrantTypes:{'urn:foo:bar:baz':MyGrantType}};
For information on how to implement a handler for a custom grant type seeExtension Grants.
constoauth=newOAuth2Server({model:...});functiontokenHandler(options){returnfunction(req,res,next){letrequest=newRequest(req);letresponse=newResponse(res);returnoauth.token(request,response,options).then(function(code){res.locals.oauth={token:token};next();}).catch(function(err){// handle error condition});}}