Skip to content

OAuth2Server

The main OAuth2 server class.

Kind: global class

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:

  • InvalidArgumentError if the model is missing
ParamTypeDefaultDescription
optionsobjectServer options.
options.modelModelThe Model; this is always required.
options.scopeArray.<string> | undefinedThe scope(s) to authenticate.
[options.addAcceptedScopesHeader]booleantrueSet the X-Accepted-OAuth-Scopes HTTP header on response objects.
[options.addAuthorizedScopesHeader]booleantrueSet the X-OAuth-Scopes HTTP header on response objects.
[options.allowBearerTokensInQueryString]booleanfalseAllow clients to pass bearer tokens in the query string of a request.
[options.authenticateHandler]objectThe authenticate handler (see remarks section).
options.authenticateHandler.handlefunctionThe actual handler function to get an authenticated user
[options.allowEmptyState]booleanfalseAllow clients to specify an empty `state
[options.authorizationCodeLifetime]number300Lifetime of generated authorization codes in seconds (default = 300 s = 5 min)
[options.accessTokenLifetime]number3600Lifetime of generated access tokens in seconds (default = 1 hour).
[options.refreshTokenLifetime]number1209600Lifetime of generated refresh tokens in seconds (default = 2 weeks).
[options.allowExtendedTokenAttributes]booleanfalseAllow extended attributes to be set on the returned token (see remarks section).
[options.requireClientAuthentication]object | booleanobjectRequire a client secret for grant types (names as keys). Defaults to true for all grant types.
[options.alwaysIssueNewRefreshToken]booleantrueAlways revoke the used refresh token and issue a new one for the refresh_token grant.
[options.extendedGrantTypes]objectobjectAdditional supported grant types.

Example

js
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:

  • UnauthorizedRequestError The protected resource request failed authentication.
ParamTypeDefaultDescription
options.scopeArray.<string> | undefinedThe scope(s) to authenticate.
[options.addAcceptedScopesHeader]booleantrueSet the X-Accepted-OAuth-Scopes HTTP header on response objects.
[options.addAuthorizedScopesHeader]booleantrueSet the X-OAuth-Scopes HTTP header on response objects.
[options.allowBearerTokensInQueryString]booleanfalseAllow clients to pass bearer tokens in the query string of a request.

Example

js
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.

js
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:

js
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:

  • AccessDeniedError The resource owner denied the access request (i.e. request.query.allow was 'false').
ParamTypeDefaultDescription
requestRequestthe Request instance object
[request.query.allowed]string'false' to deny the authorization request (see remarks section).
responseResponsethe Response instance object
[options]objecthandler options
[options.authenticateHandler]objectThe authenticate handler (see remarks section).
options.authenticateHandler.handlefunctionThe actual handler function to get an authenticated user
[options.allowEmptyState]booleanfalseAllow clients to specify an empty `state
[options.authorizationCodeLifetime]number300Lifetime of generated authorization codes in seconds (default = 300 s = 5 min)

Example

js
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.

js
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:

js
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:

  • InvalidGrantError The access token request was invalid or not authorized.
ParamTypeDefaultDescription
requestRequestthe Request instance object
responseResponsethe Response instance object
[options]objecthandler options
[options.accessTokenLifetime]number3600Lifetime of generated access tokens in seconds (default = 1 hour).
[options.refreshTokenLifetime]number1209600Lifetime of generated refresh tokens in seconds (default = 2 weeks).
[options.allowExtendedTokenAttributes]booleanfalseAllow extended attributes to be set on the returned token (see remarks section).
[options.requireClientAuthentication]object | booleanobjectRequire a client secret for grant types (names as keys). Defaults to true for all grant types.
[options.alwaysIssueNewRefreshToken]booleantrueAlways revoke the used refresh token and issue a new one for the refresh_token grant.
[options.extendedGrantTypes]objectobjectAdditional supported grant types.

Example

js
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
      });
  }
}