OAuth2Server
The main OAuth2 server class.
Kind: global class
- OAuth2Server
- new OAuth2Server(options)
- .authenticate() ⇒
Promise.<object> - .authorize(request, response, [options]) ⇒
Promise.<object> - .token(request, response, [options]) ⇒
Promise.<object>
new OAuth2Server(options)
Instantiates OAuth2Server using the supplied model. Remarks:
- Any valid option for authenticate, authorize and token can be passed to the constructor as well.
- The supplied options will be used as default for the other methods.
Returns: OAuth2Server - A new OAuth2Server instance.
Throws:
InvalidArgumentErrorif the model is missing
| Param | Type | Default | Description |
|---|---|---|---|
| options | object | Server options. | |
| options.model | Model | The Model; this is always required. | |
| options.scope | Array.<string> | undefined | The scope(s) to authenticate. | |
| [options.addAcceptedScopesHeader] | boolean | true | Set the X-Accepted-OAuth-Scopes HTTP header on response objects. |
| [options.addAuthorizedScopesHeader] | boolean | true | Set the X-OAuth-Scopes HTTP header on response objects. |
| [options.allowBearerTokensInQueryString] | boolean | false | Allow clients to pass bearer tokens in the query string of a request. |
| [options.authenticateHandler] | object | The authenticate handler (see remarks section). | |
| options.authenticateHandler.handle | function | The actual handler function to get an authenticated user | |
| [options.allowEmptyState] | boolean | false | Allow clients to specify an empty `state |
| [options.authorizationCodeLifetime] | number | 300 | Lifetime of generated authorization codes in seconds (default = 300 s = 5 min) |
| [options.accessTokenLifetime] | number | 3600 | Lifetime of generated access tokens in seconds (default = 1 hour). |
| [options.refreshTokenLifetime] | number | 1209600 | Lifetime of generated refresh tokens in seconds (default = 2 weeks). |
| [options.allowExtendedTokenAttributes] | boolean | false | Allow extended attributes to be set on the returned token (see remarks section). |
| [options.requireClientAuthentication] | object | boolean | object | Require a client secret for grant types (names as keys). Defaults to true for all grant types. |
| [options.alwaysIssueNewRefreshToken] | boolean | true | Always revoke the used refresh token and issue a new one for the refresh_token grant. |
| [options.extendedGrantTypes] | object | object | Additional supported grant types. |
Example
const OAuth2Server = require('@node-oauth/oauth2-server');oAuth2Server.authenticate() ⇒ Promise.<object>
Authenticates a request.
Kind: instance method of OAuth2Server
Returns: Promise.<object> - A Promise that resolves to the access token object returned from the model's getAccessToken. In case of an error, the promise rejects with one of the error types derived from OAuthError.
Throws:
UnauthorizedRequestErrorThe protected resource request failed authentication.
| Param | Type | Default | Description |
|---|---|---|---|
| options.scope | Array.<string> | undefined | The scope(s) to authenticate. | |
| [options.addAcceptedScopesHeader] | boolean | true | Set the X-Accepted-OAuth-Scopes HTTP header on response objects. |
| [options.addAuthorizedScopesHeader] | boolean | true | Set the X-OAuth-Scopes HTTP header on response objects. |
| [options.allowBearerTokensInQueryString] | boolean | false | Allow clients to pass bearer tokens in the query string of a request. |
Example
const oauth = new OAuth2Server({model: ...});
function authenticateHandler(options) {
return function(req, res, next) {
let request = new Request(req);
let response = new Response(res);
return oauth.authenticate(request, response, options)
.then(function(token) {
res.locals.oauth = {token: token};
next();
})
.catch(function(err) {
// handle error condition
});
}
}oAuth2Server.authorize(request, response, [options]) ⇒ Promise.<object>
Authorizes a token request. Remarks:
If request.query.allowed equals the string 'false' the access request is denied and the returned promise is rejected with an AccessDeniedError.
In order to retrieve the user associated with the request, options.authenticateHandler should be supplied. The authenticateHandler has to be an object implementing a handle(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.
let authenticateHandler = {
handle: function(request, response) {
return // get authenticated user;
}
};When working with a session-based login mechanism, the handler can simply look like this:
let authenticateHandler = {
handle: function(request, response) {
return request.session.user;
}
};Kind: instance method of OAuth2Server
Returns: Promise.<object> - A Promise that resolves to the authorization code object returned from model's saveAuthorizationCode In case of an error, the promise rejects with one of the error types derived from OAuthError.
Throws:
AccessDeniedErrorThe resource owner denied the access request (i.e.request.query.allowwas'false').
| Param | Type | Default | Description |
|---|---|---|---|
| request | Request | the Request instance object | |
| [request.query.allowed] | string | 'false' to deny the authorization request (see remarks section). | |
| response | Response | the Response instance object | |
| [options] | object | handler options | |
| [options.authenticateHandler] | object | The authenticate handler (see remarks section). | |
| options.authenticateHandler.handle | function | The actual handler function to get an authenticated user | |
| [options.allowEmptyState] | boolean | false | Allow clients to specify an empty `state |
| [options.authorizationCodeLifetime] | number | 300 | Lifetime of generated authorization codes in seconds (default = 300 s = 5 min) |
Example
const oauth = new OAuth2Server({model: ...});
function authorizeHandler(options) {
return function(req, res, next) {
let request = new Request(req);
let response = new Response(res);
return oauth.authorize(request, response, options)
.then(function(code) {
res.locals.oauth = {code: code};
next();
})
.catch(function(err) {
// handle error condition
});
}
}oAuth2Server.token(request, response, [options]) ⇒ Promise.<object>
Retrieves a new token for an authorized token request. Remarks: If options.allowExtendedTokenAttributes is true any additional properties set on the object returned from Model#saveToken() <Model#saveToken> are copied to the token response sent to the client. By default, all grant types require the client to send it's client_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 to true or false. Possible keys for the object include all supported values for the token request's grant_type field (authorization_code, client_credentials, password and refresh_token). Grants that are not specified default to true which enables verification of the client_secret.
let options = {
// ...
// 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:
let options = {
// ...
extendedGrantTypes: {
'urn:foo:bar:baz': MyGrantType
}
};For information on how to implement a handler for a custom grant type see the extension grants.
Kind: instance method of OAuth2Server
Returns: Promise.<object> - A Promise that resolves to the token object returned from the model's saveToken method. In case of an error, the promise rejects with one of the error types derived from OAuthError.
Throws:
InvalidGrantErrorThe access token request was invalid or not authorized.
| Param | Type | Default | Description |
|---|---|---|---|
| request | Request | the Request instance object | |
| response | Response | the Response instance object | |
| [options] | object | handler options | |
| [options.accessTokenLifetime] | number | 3600 | Lifetime of generated access tokens in seconds (default = 1 hour). |
| [options.refreshTokenLifetime] | number | 1209600 | Lifetime of generated refresh tokens in seconds (default = 2 weeks). |
| [options.allowExtendedTokenAttributes] | boolean | false | Allow extended attributes to be set on the returned token (see remarks section). |
| [options.requireClientAuthentication] | object | boolean | object | Require a client secret for grant types (names as keys). Defaults to true for all grant types. |
| [options.alwaysIssueNewRefreshToken] | boolean | true | Always revoke the used refresh token and issue a new one for the refresh_token grant. |
| [options.extendedGrantTypes] | object | object | Additional supported grant types. |
Example
const oauth = new OAuth2Server({model: ...});
function tokenHandler(options) {
return function(req, res, next) {
let request = new Request(req);
let response = new Response(res);
return oauth.token(request, response, options)
.then(function(code) {
res.locals.oauth = {token: token};
next();
})
.catch(function(err) {
// handle error condition
});
}
}