Arrow keys: ← previous · → next 34 of 37
@nodedk/oauth
0.1.0 experimental server

oauth#

OAuth authorization codes, PKCE and rotating refresh tokens for Node.js.

Requirements#

A MongoDB-compatible database. Your app provides HTTPS, login and user consent.

Usage#

Create an instance with your database and registered clients:

var createOAuth = require('@nodedk/oauth')

module.exports = function (db) {
  return createOAuth({
    db,
    issuer: 'https://app.example',
    resources: ['https://app.example/api'],
    clients: [
      {
        client_id: 'editor',
        redirect_uris: ['https://editor.example/callback'],
        scopes: ['read', 'write']
      }
    ]
  })
}

Add client_secret to a client to use HTTP Basic authentication. Set token_endpoint_auth_method: 'client_secret_post' to also accept form credentials. All clients use S256 PKCE.

API#

createOAuth(config)#

Returns the OAuth instance synchronously. Uses the database's oauth collection. Token lifetimes are configured in seconds: code_lifetime defaults to 60, access_lifetime to 3600, and refresh_lifetime to 2592000. Authorization code lifetimes must be between 1 and 600 seconds.

oauth.authorize(params, owner, res?)#

Call after login and approval. owner identifies the user who granted access. Pass null to deny access.

var url = new URL(req.url, 'https://app.example')
await oauth.authorize(url.searchParams, owner, res)

Requests need client_id, response_type=code, an explicit scope, code_challenge and code_challenge_method=S256. Include resource when resources are configured. redirect_uri may be omitted when only one callback is registered. Optional state is echoed back. Callbacks must use HTTPS, public-client loopback HTTP, or a private-use native application scheme containing a period, such as com.example.app.

Without res, returns the callback URL or throws an error.

oauth.token(req, res?)#

Handles authorization-code exchange and refresh requests:

await oauth.token(req, res)

Pass the unread Node.js request stream. It must be a URL-encoded POST with grant_type=authorization_code or grant_type=refresh_token and the corresponding credentials. Code exchange requires the PKCE verifier and, when originally supplied, the same redirect URI.

Without res, returns { access_token, token_type, expires_in, refresh_token, scope }. Always save the replacement refresh token. Refreshing invalidates the previous access token; reusing an old refresh token revokes the grant.

oauth.verify(accessToken, resource?)#

var grant = await oauth.verify(accessToken, 'https://app.example/api')

Returns { grant, owner, client_id, scope, resource }, or null for an invalid token. The resource defaults to the only configured resource. Your app checks the returned scopes and owner before allowing access.

oauth.revoke(grantId)#

await oauth.revoke(grant.grant)

Revokes the grant and its tokens. Pass the grant ID returned by verify(), not the access token. Repeated calls are safe.

oauth.metadata(resource?)#

var server = oauth.metadata()
var resource = oauth.metadata('https://app.example/api')

Returns discovery metadata. Requires issuer. For the configuration above, serve these objects as JSON at /.well-known/oauth-authorization-server and /.well-known/oauth-protected-resource/api. Authorization and token endpoints are advertised at /oauth/authorize and /oauth/token under the issuer URL.

oauth.challenge(options = {})#

res.statusCode = 401
res.setHeader('www-authenticate', oauth.challenge({
  error: 'invalid_token'
}))
res.end()

Returns a Bearer challenge. Options are resource, scope and error. Omit error when no credentials were supplied. Use insufficient_scope with HTTP 403 when a valid token lacks the required permission.

Errors#

Passing res to authorize() or token() sends and ends the redirect, JSON or error response, including cache headers. Otherwise, errors expose oauth, statusCode, optional headers and a validated redirect URL when applicable.

Created by Vidar Eldøy

Tools for business systems.