Skip to content

Classes

Model

The Model implements the interface through which some aspects of storage, retrieval and custom validation are abstracted.

Each model function is resolved async by default. This implies that async and sync model functions, as well as generators, are supported.

Typedefs

AccessTokenData

An Object representing the access token and associated data. token.client and token.user can carry additional properties that will be ignored by oauth2-server.

RefreshTokenData

An Object representing the refresh token and associated data. token.client and token.user can carry additional properties that will be ignored by oauth2-server.

AuthorizationCodeData

An Object representing the authorization code and associated data. code.client and code.user can carry additional properties that will be ignored by oauth2-server.

ClientData

An Object representing the client and associated data.

Model

The Model implements the interface through which some aspects of storage, retrieval and custom validation are abstracted.

Each model function is resolved async by default. This implies that async and sync model functions, as well as generators, are supported.

Kind: global class

new Model()

Example

js
const model = Model.from({
    getClient: () => { ... }
})

model.getClient(clientId, clientSecret) ⇒ Promise.<ClientData>

Invoked to retrieve a client using a client id or a client id/client secret combination, depending on the grant type. This model function is required for all grant types. Invoked during:

  • authorization_code grant
  • client_credentials grant
  • refresh_token grant
  • password grant

Kind: instance method of Model
Fulfil: ClientData - An Object representing the client and associated data, or a falsy value if no such client could be found.
Reject: Error - An Error type

ParamTypeDescription
clientIdstringThe client id of the client to retrieve.
clientSecretstringThe client secret of the client to retrieve. Can be null.

model.saveToken(token, client, user) ⇒ Promise.<object>

Invoked to save an access token and optionally a refresh token, depending on the grant type. This model function is required for all grant types.

Invoked during:

  • authorization_code grant
  • client_credentials grant
  • refresh_token grant
  • password grant

If the allowExtendedTokenAttributes server option is enabled (see OAuth2Server#token() <OAuth2Server#token>) any additional attributes set on the result are copied to the token response sent to the client.

Kind: instance method of Model
Fulfil: {accessToken:string,accessTokenExpiresAt:Date,refreshToken: string,refreshTokenExpiresAt: Date,scope: string[],client: ClientData,user: object} An Object representing the token(s) and associated data.

ParamTypeDescription
tokenobjectThe token(s) to be saved.
token.accessTokenstringThe access token to be saved.
token.accessTokenExpiresAtDateThe expiry time of the access token.
token.refreshTokenstringThe refresh token to be saved.
token.refreshTokenExpiresAtDateThe expiry time of the refresh token.
token.scopeArray.<string>The authorized scope of the token(s)
clientClientDataThe client associated with the token(s).
userobjectThe user associated with the token(s).

Example

js
function saveToken(token, client, user) {
  // imaginary DB queries
  let fns = [
    db.saveAccessToken({
      access_token: token.accessToken,
      expires_at: token.accessTokenExpiresAt,
      scope: token.scope,
      client_id: client.id,
      user_id: user.id
    }),
    db.saveRefreshToken({
      refresh_token: token.refreshToken,
      expires_at: token.refreshTokenExpiresAt,
      scope: token.scope,
      client_id: client.id,
      user_id: user.id
    })
  ];
  return Promise.all(fns);
    .spread(function(accessToken, refreshToken) {
      return {
        accessToken: accessToken.access_token,
        accessTokenExpiresAt: accessToken.expires_at,
        refreshToken: refreshToken.refresh_token,
        refreshTokenExpiresAt: refreshToken.expires_at,
        scope: accessToken.scope,
        client: {id: accessToken.client_id},
        user: {id: accessToken.user_id}
      };
    });
}

model.getUser(username, password, [client]) ⇒ Promise.<(object|null|undefined|false|0)>

Deprecated

Invoked to retrieve a user using a username/password combination. This model function is required if the password grant is used. Please note, that password grant is considered unsafe. It is still supported but marked deprecated.

Invoked during:

  • password grant

Kind: instance method of Model
Returns: Promise.<(object|null|undefined|false|0)> - An Object representing the user, or a falsy value if no such user could be found. The user object is completely transparent to oauth2-server and is simply used as input to other model functions.

ParamTypeDescription
usernamestringThe username of the user to retrieve.
passwordstringThe user's password.
[client]ClientDataThe client.

Example

js
function getUser(username, password) {
  // imaginary DB query
  return db.queryUser({username: username, password: password});
}

model.getUserFromClient(client) ⇒ Promise.<object>

Invoked to retrieve the user associated with the specified client. This model function is required if the client_credentials grant is used.

Invoked during:

  • client_credentials grant

Remarks:

client is the object previously obtained through Model#getClient() <Model#getClient>.

Kind: instance method of Model
Returns: Promise.<object> - An Object representing the user, or a falsy value if the client does not have an associated user. The user object is completely transparent to oauth2-server and is simply used as input to other model functions.

ParamTypeDescription
clientClientDataThe client to retrieve the associated user for.

Example

js
function getUserFromClient(client) {
  // imaginary DB query
  return db.queryUser({id: client.user_id});
}

model.getAccessToken(accessToken) ⇒ Promise.<AccessTokenData>

Invoked to retrieve an existing access token, including associated data, that has previously been saved through Model#saveToken() <Model#saveToken>. This model function is required if OAuth2Server#authenticate() <OAuth2Server#authenticate> is used.

Invoked during:

  • request authentication

Kind: instance method of Model
Returns: Promise.<AccessTokenData> - the object, containing the data, stored with the access token

ParamTypeDescription
accessTokenstringThe access token to retrieve.

Example

js
function getAccessToken(accessToken) {
  // imaginary DB queries
  return db.queryAccessToken({access_token: accessToken})
    .then(function(token) {
      return Promise.all([
        token,
        db.queryClient({id: token.client_id}),
        db.queryUser({id: token.user_id})
      ]);
    })
    .spread(function(token, client, user) {
      return {
        accessToken: token.access_token,
        accessTokenExpiresAt: token.expires_at,
        scope: token.scope,
        client: client, // with 'id' property
        user: user
      };
    });
}

model.getRefreshToken(refreshToken) ⇒ Promise.<RefreshTokenData>

Invoked to retrieve an existing refresh token previously saved through Model#saveToken() <Model#saveToken>. This model function is required if the refresh_token grant is used. Invoked during:

  • refresh_token grant

Kind: instance method of Model
Returns: Promise.<RefreshTokenData> - An Object representing the refresh token and associated data.

ParamTypeDescription
refreshTokenstringThe access token to retrieve.

Example

js
function getRefreshToken(refreshToken) {
  // imaginary DB queries
  return db.queryRefreshToken({refresh_token: refreshToken})
    .then(function(token) {
      return Promise.all([
        token,
        db.queryClient({id: token.client_id}),
        db.queryUser({id: token.user_id})
      ]);
    })
    .spread(function(token, client, user) {
      return {
        refreshToken: token.refresh_token,
        refreshTokenExpiresAt: token.expires_at,
        scope: token.scope,
        client: client, // with 'id' property
        user: user
      };
    });
}

model.getAuthorizationCode(authorizationCode) ⇒ Promise.<AuthorizationCodeData>

Invoked to retrieve an existing authorization code previously saved through Model#saveAuthorizationCode() <Model#saveAuthorizationCode>. This model function is required if the authorization_code grant is used. Invoked during:

  • authorization_code grant

Kind: instance method of Model
Returns: Promise.<AuthorizationCodeData> - An Object representing the authorization code and associated data.

ParamTypeDescription
authorizationCodestringThe authorization code to retrieve.

Example

js
function getAuthorizationCode(authorizationCode) {
  // imaginary DB queries
  return db.queryAuthorizationCode({authorization_code: authorizationCode})
    .then(function(code) {
      return Promise.all([
        code,
        db.queryClient({id: code.client_id}),
        db.queryUser({id: code.user_id})
      ]);
    })
    .spread(function(code, client, user) {
      return {
        authorizationCode: code.authorization_code,
        expiresAt: code.expires_at,
        redirectUri: code.redirect_uri,
        scope: code.scope,
        client: client, // with 'id' property
        user: user
      };
    });
}

model.saveAuthorizationCode(code, client, user) ⇒ Promise.<object>

Invoked to save an authorization code. This model function is required if the authorization_code grant is used.

Invoked during:

  • authorization_code grant

Kind: instance method of Model
Fulfil: { authorizationCode: string, expiresAt: Date, redirectUri: string,scope: string[],client: ClientData,user: object} An Object representing the authorization code and associated data. code.client and code.user can carry additional properties that will be ignored by oauth2-server.

ParamTypeDescription
codeobjectThe code to be saved.
code.authorizationCodestringThe authorization code to be saved.
code.expiresAtDateThe expiry time of the authorization code.
code.redirectUristringThe redirect URI associated with the authorization code.
code.scopeArray.<string>The authorized scope of the authorization code.
clientClientDataThe client associated with the authorization code.
userobjectThe user associated with the authorization code.

Example

js
function saveAuthorizationCode(code, client, user) {
  // imaginary DB queries
  let authCode = {
    authorization_code: code.authorizationCode,
    expires_at: code.expiresAt,
    redirect_uri: code.redirectUri,
    scope: code.scope,
    client_id: client.id,
    user_id: user.id
  };
  return db.saveAuthorizationCode(authCode)
    .then(function(authorizationCode) {
      return {
        authorizationCode: authorizationCode.authorization_code,
        expiresAt: authorizationCode.expires_at,
        redirectUri: authorizationCode.redirect_uri,
        scope: authorizationCode.scope,
        client: {id: authorizationCode.client_id},
        user: {id: authorizationCode.user_id}
      };
    });
}

model.revokeToken(token) ⇒ Promise.<boolean>

Invoked to revoke a refresh token. This model function is required if the refresh_token grant is used. Invoked during:

  • refresh_token grant

Remarks:token is the refresh token object previously obtained through Model#getRefreshToken() <Model#getRefreshToken>.

Kind: instance method of Model
Returns: Promise.<boolean> - Return true if the revocation was successful or false if the refresh token could not be found.

ParamType
tokenRefreshTokenData

Example

js
function revokeToken(token) {
  // imaginary DB queries
  return db.deleteRefreshToken({refresh_token: token.refreshToken})
    .then(function(refreshToken) {
      return !!refreshToken;
    });
}

model.revokeAuthorizationCode(code) ⇒ Promise.<boolean>

Invoked to revoke an authorization code. This model function is required if the authorization_code grant is used.

Invoked during:

  • authorization_code grant

Remarks:code is the authorization code object previously obtained through getAuthorizationCode.

Kind: instance method of Model
Returns: Promise.<boolean> - Return true if the revocation was successful or false if the authorization code could not be found.

ParamType
codeAuthorizationCodeData

model.verifyScope(accessToken, scope) ⇒ Promise.<boolean>

Invoked during request authentication to check if the provided access token was authorized the requested scopes.

This model function is required if scopes are used with OAuth2Server#authenticate() <OAuth2Server#authenticate> but it's never called, if you provide your own authenticateHandler to the options.

Invoked during:

  • request authentication

Remarks:

  • token is the access token object previously obtained through Model#getAccessToken() <Model#getAccessToken>.
  • scope is the required scope as given to OAuth2Server#authenticate() <OAuth2Server#authenticate> as options.scope.

Kind: instance method of Model
Returns: Promise.<boolean> - Returns true if the access token passes, false otherwise.

ParamTypeDescription
accessTokenAccessTokenData
scopeArray.<string>The required scopes.

Example

js
function verifyScope(token, requestedScopes) {
  if (!token.scope) {
    return false;
  }
  let authorizedScopes = token.scope;
  return requestedScopes.every(s => authorizedScopes.includes(s));
}

model.generateAccessToken(client, user, scope) ⇒ Promise.<string>

Invoked to generate a new access token. This model function is optional.

If not implemented, a default handler is used that generates access tokens consisting of 40 characters in the range of a..z0..9. RFC 6749 Appendix A.12 specifies that access tokens must consist of characters inside the range 0x20..0x7E (i.e. only printable US-ASCII characters).

Invoked during:

  • authorization_code grant
  • client_credentials grant
  • refresh_token grant
  • password grant

Remarks:

  • client is the object previously obtained through Model#getClient() <Model#getClient>.
  • user is the user object previously obtained through Model#getAuthorizationCode() <Model#getAuthorizationCode> (code.user; authorization code grant), Model#getUserFromClient() <Model#getUserFromClient> (client credentials grant), Model#getRefreshToken() <Model#getRefreshToken> (token.user; refresh token grant) or Model#getUser() <Model#getUser> (password grant).

Kind: instance method of Model
Returns: Promise.<string> - A String to be used as access token.

ParamTypeDescription
clientobjectThe client the access token is generated for
userobjectThe user the access token is generated for.
scopeArray.<string>The scopes associated with the token. Can be null

model.generateRefreshToken(client, user, scope) ⇒ Promise.<string>

Invoked to generate a new refresh token.

This model function is optional. If not implemented, a default handler is used that generates refresh tokens consisting of 40 characters in the range of a..z0..9. RFC 6749 Appendix A.17 specifies that refresh tokens must consist of characters inside the range 0x20..0x7E (i.e. only printable US-ASCII characters).

Invoked during:

  • authorization_code grant
  • refresh_token grant
  • password grant

Remarks:

client is the object previously obtained through Model#getClient() <Model#getClient>.

user is the user object previously obtained through Model#getAuthorizationCode() <Model#getAuthorizationCode> (code.user; authorization code grant), Model#getRefreshToken() <Model#getRefreshToken> (token.user; refresh token grant) or Model#getUser() <Model#getUser> (password grant).

Kind: instance method of Model
Returns: Promise.<string> - A String to be used as refresh token.

ParamTypeDescription
clientobjectThe client the refresh token is generated for
userobjectThe user the refresh token is generated for.
scopeArray.<string>The scopes associated with the refresh token. Can be null

model.generateAuthorizationCode(client, user, scope) ⇒ Promise.<string>

Invoked to generate a new authorization code. This model function is optional. If not implemented, a default handler is used that generates authorization codes consisting of 40 characters in the range of a..z0..9. RFC 6749 Appendix A.11 specifies that authorization codes must consist of characters inside the range 0x20..0x7E (i.e. only printable US-ASCII characters).

Invoked during:

  • authorization_code grant

`

Kind: instance method of Model
Returns: Promise.<string> - A String to be used as authorization code.

ParamTypeDescription
clientobjectThe client the authorization code is generated for.
userobjectThe user the authorization code is generated for.
scopeArray.<string>The scopes associated with the authorization code. Can be null.

model.validateScope(user, client, scope) ⇒ Promise.<boolean>

Invoked to check if the requested scope is valid for a particular client/user combination.

This model function is optional. If not implemented, any scope is accepted.

Invoked during:

  • authorization_code grant
  • client_credentials grant
  • password grant

Remarks:

user is the user object previously obtained through Model#getAuthorizationCode() <Model#getAuthorizationCode> (code.user; authorization code grant), Model#getUserFromClient() <Model#getUserFromClient> (client credentials grant) or Model#getUser() <Model#getUser> (password grant).

client is the object previously obtained through Model#getClient <Model#getClient> (all grants).

You can decide yourself whether you want to reject or accept partially valid scopes by simply filtering out invalid scopes and returning only the valid ones.

Kind: instance method of Model
Returns: Promise.<boolean> - Validated scopes to be used or a falsy value to reject the requested scopes.

ParamTypeDescription
userobjectThe associated user.
clientClientDataThe associated client.
scopeArray.<string>The scopes to validate.

Example

js
// To reject invalid or only partially valid scopes:
const VALID_SCOPES = ['read', 'write'];
function validateScope(user, client, scope) {
  if (!scope.every(s => VALID_SCOPES.indexOf(s) >= 0)) {
    return false;
  }
  return scope;
}

Example

js
// To accept partially valid scopes:
const VALID_SCOPES = ['read', 'write'];
function validateScope(user, client, scope) {
  return scope.filter(s => VALID_SCOPES.indexOf(s) >= 0);
}

model.validateRedirectUri(redirectUri, client) ⇒ Promise.<boolean>

Invoked to check if the provided redirectUri is valid for a particular client. This model function is optional. If not implemented, the redirectUri should be included in the provided redirectUris of the client.

Invoked during:

  • authorization_code grant

Remarks: When implementing this method you should take care of possible security risks related to redirectUri. See: https://datatracker.ietf.org/doc/html/rfc6819 (Section-5.2.3.5 is implemented by default).

Kind: instance method of Model
Returns: Promise.<boolean> - Returns true if the redirectUri is valid, false otherwise.

ParamTypeDescription
redirectUristringThe redirect URI to validate
clientobjectThe associated client.

Model.from(impl) ⇒ Model

Factory function to create a model form your implementation.

Kind: static method of Model
Returns: Model - the model instance.

ParamTypeDescription
implobjectan object containing your model function implementations

AccessTokenData

An Object representing the access token and associated data. token.client and token.user can carry additional properties that will be ignored by oauth2-server.

Kind: global typedef
Properties

NameTypeDescription
accessTokenstringThe access token passed to getAccessToken()
accessTokenExpiresAtDateThe expiry time of the access token.
scopeArray.<string>The authorized scope of the access token.
clientobjectThe client associated with the access token.
client.idstringA unique string identifying the client.
userobjectThe user associated with the access token.

RefreshTokenData

An Object representing the refresh token and associated data. token.client and token.user can carry additional properties that will be ignored by oauth2-server.

Kind: global typedef
Properties

NameTypeDescription
refreshTokenstringThe refresh token passed to getRefreshToken()
refreshTokenExpiresAtDateThe expiry time of the refresh token.
scopeArray.<string>The authorized scope of the refresh token.
clientClientDataThe client associated with the refresh token.
userobjectThe user associated with the access token.

AuthorizationCodeData

An Object representing the authorization code and associated data. code.client and code.user can carry additional properties that will be ignored by oauth2-server.

Kind: global typedef
Properties

NameTypeDescription
codestringThe authorization code passed to getAuthorizationCode().
expiresAtDateThe expiry time of the authorization code.
redirectUristringThe redirect URI of the authorization code.
scopeArray.<string>The authorized scope of the authorization code.
clientClientDataThe client associated with the authorization code.
userobjectThe user associated with the access token.

ClientData

An Object representing the client and associated data.

Kind: global typedef
Properties

NameTypeDescription
idstringThe authorization code passed to getAuthorizationCode().
redirectUrisArray.<string>Redirect URIs allowed for the client. Required for the authorization_code grant.
grantsArray.<string>Grant types allowed for the client.
accessTokenLifetimenumberClient-specific lifetime of generated access tokens in seconds.
refreshTokenLifetimenumberClient-specific lifetime of generated refresh tokens in seconds.