Module Server Express

@byu-oit-sdk/express

Requirements:

  • Node.js 18+
    • or Node.js 10+ with fetch and crypto polyfills
  • npm v9+
  • Express v4

Install

In addition to installing this module, you must install and configure a compatible store. Currently only session-dynamo is supported.

npm i @byu-oit-sdk/express @byu-oit-sdk/session-dynamo

Introduction

Use this module to configure express servers that need to implement the OAuth 2.0 Authorization Code grant type.

This module assumes that the access token returned after the authorization code exchange will be a jwt that it can decode to extract user information. This behavior is configurable by passing in the userInfoCallback or getIdToken function into the middleware configuration.

Signing In

  1. For a user to log in, the browser should direct the user to the logIn route.
  2. After the user logs in, the server will redirect the user to the location provided in the redirect query parameter from the login step, or falls back to the logInRedirect option passed into the configuration.
  3. If the user encounters an error, they will be redirected to errorRedirect and an error message will be displayed in the query parameters of the url.

Signing Out

  1. For a user to log out, the browser should direct the user to thelogOut route.
  2. When the user logs out, their session is cleared but the token is not revoked.
  3. After logging out, they will be redirected to the logOutRedirect route.
  4. If the user encounters an error, they will be redirected to errorRedirect and an error message will be displayed in the query parameters of the url.

Options

The list below includes both options set in code and environment variables that you can set. Client id and redirect uri are both part of the AuthorizationCodeProvider options object, read more about that for further information.

Option Environment Name Type Default Description
logIn - string /signin The path which redirects the caller to the authorization url to sign in.
logInRedirect - string / The path to redirect the caller to after signing in.
logOut - string /signout The path to call to clear a user's session and revoke the access token.
logOutRedirect - string / The path to redirect the caller to after signing out.
errorRedirect - string /auth/error The path to redirect the caller to after an error is encountered during the authorization flow.
userInfoCookieName - string user_info The name of the cookie containing the user information parsed from the token.
getIdToken - function (returns the access token) Configures how the package gets the id token.
userInfoCallback - function (returns the decoded token using the getIdToken function) Configures how the package gets the user information.
clientId BYU_OIT_CLIENT_ID string - The client identifier issued to the client during the registration process.
clientSecret BYU_OIT_CLIENT_SECRET string - The client secret of the account being used.
redirectUri BYU_OIT_REDIRECT_URI string - The redirection endpoint that the authorization server should redirect to after authenticating the resource owner.
discoveryEndpoint BYU_OIT_DISCOVERY_ENDPOINT string - Used to configure where the user will be sent to sign in.

Overriding default options

To override the default settings listed above, pass an AuthorizationCodePluginOptions object into the AuthorizationCodeFlow with the desired settings.

JavaScript Code Example
import { AuthorizationCodeFlow, byuOitGetIdToken as getIdToken } from '@byu-oit-sdk/express'
const app = Express()

// ... add middleware to app

AuthorizationCodeFlow(app, {
logIn: 'myRoute/myLoginEndpoint',
getIdToken
})

// ... add middleware to app

// run the app
TypeScript Code Example
import { AuthorizationCodeFlow, byuOitGetIdToken as getIdToken } from '@byu-oit-sdk/express'
const app = Express()

// ... add middleware to app

AuthorizationCodeFlow(app, {
logIn: 'myRoute/myLoginEndpoint',
getIdToken
})

// ... add middleware to app

// run the app

Every member of AuthorizationCodePluginOptions is optional. You are only required to specify the specific default values they want to override.

Usage

To use the package with default settings, pass your express application into the Authorization Code Flow function

JavaScript Code Example
import env from 'env-var'
import { LoggerMiddleware } from '@byu-oit/express-logger'
import { AuthorizationCodeFlow } from '@byu-oit-sdk/express'
import express from 'express'
import { SessionMiddleware } from '@byu-oit-sdk/session-express'

export const app = express()

const secret = env.get('BYU_OIT_SIGNING_SECRET').required().asString()
const isProduction = env.get('NODE_ENV').default('development').asEnum(['production', 'development']) === 'production'

let store
if (isProduction) {
const client = new DynamoDBClient({
region: env.get('AWS_REGION').required().asString(),
endpoint: 'http://localhost:8000'
})
store = new DynamoSessionStore({ client, tableName: 'sessions' })
}

/**
* Must register the @byu-oit-sdk/session-express middleware. You must pass in a session storage option for production environments.
* Using the default in-memory storage is highly discouraged because it will cause memory leaks.
*/
const sessionMiddleware = await SessionMiddleware({ store })
app.use(sessionMiddleware)

/**
* Attach the logger to the express instance
*/
app.use(LoggerMiddleware())

/**
* Use the package here
*/
await AuthorizationCodeFlow(app)

/**
* To require authentication for a route, just specify the authenticate function on the request object in the onRequest hook.
*/
app.get('/auth/user', (req, res) => {
res.send(`Your CES UUID is ${req.session.user.cesUUID}`)
})

/**
* This is an extremely rudimentary error handler. Error handlers should always be attached to the application last, in order to
* catch any errors that are thrown
*/
app.use((err, req, res, _next) => {
console.error(err.stack)
res.status(500).send('Something broke!')
})
TypeScript Code Example
import env from 'env-var'
import { LoggerMiddleware } from '@byu-oit/express-logger'
import { AuthorizationCodeFlow, autoAuthenticate } from '@byu-oit-sdk/express'
import express, { type Response } from 'express'
import SessionMiddleware from '@byu-oit-sdk/session-express'
import type { Request } from 'express-serve-static-core'
import { createDecoder } from 'fast-jwt'
import { DynamoSessionStore } from '@byu-oit-sdk/session-dynamo'
import { DynamoDBClient } from '@aws-sdk/client-dynamodb'

declare module '@byu-oit-sdk/express' {
interface UserInfo {
/**
* Declare your user info object properties here
*/
}
}

export const app = express()

const secret = env.get('BYU_OIT_SIGNING_SECRET').required().asString()
const isProduction = env.get('NODE_ENV').default('development').asEnum(['production', 'development']) === 'production'

let store
if (isProduction) {
const client = new DynamoDBClient({})
store = new DynamoSessionStore({ client, tableName: 'sessions' })
}

/**
* Must register the @byu-oit-sdk/session-express middleware. You must pass in a session storage option for production environments.
* Using the default in-memory storage is highly discouraged because it will cause memory leaks.
*/
const sessionMiddleware = await SessionMiddleware({ store })
app.use(sessionMiddleware)

/**
* Attach the logger to the express instance
*/
app.use(LoggerMiddleware())

/* Initialize jwt decoder for user info callback */
const decode = createDecoder()

/**
* Attach the auth middleware we're using
*/
AuthorizationCodeFlow(app, {
/**
* A user info callback function can be supplied to implement a custom way to return the user info data.
* the default behavior is to decode the access token returned from the oauth provider token endpoint.
* The context of the `userInfoCallback` function is bound to the ExpressAuthorizationCodeProvider instance.
*/
userInfoCallback (token) {
if (typeof token.additional.id_token !== 'string') {
/** At BYU OIT the `id_token` property exists in the token response body. We can access it on the `additional` property on the token object. */
throw Error('Missing or mal-formatted ID token in response from token endpoint. Did you set the right scopes?')
}
/** Decode the `id_token` property, which should return the user info object. */
return decode(token.additional.id_token)
}
})

/**
* Create the logInRedirect route. This route should be used to handle user session data returned after the login sequence is complete.
*/
app.get('/auth/user', (req: Request, res: Response) => {
res.contentType('application/json').send(req.session.user)
})

/**
* To require authentication for a route, just use the auto-authenticate. Any routes below this middleware helper will require authentication.
*/
app.use(autoAuthenticate)

app.use((err, req, res, _next) => {
console.error(err.stack)
res.status(500).send('Something broke!')
})

Error Handling

The package does not handle errors for you. You will instead need to attach an error handler to your express application yourself. An express error handler should be attached after all other middleware has been attached. See the example above for how to attach a simple error handler

Logging in and out

This package sets up two ways for users to log in and out. The main way is to have a link that sends the user to the value passed in as logIn or logOut in the options for the AuthorizationCodeFlow() function (the default is /signin and /auth/signout, respectively). The user could even manually navigate to those routes in their browser.

Example:
<a href="/signout">Sign Out</a>
<a href="/signin">Sign In</a>

If you want to have the user be redirected to log in or log out while running server-side code, a set of functions will be added to the express res object in route handlers and such, so you can simply call res.login(<optional redirect url>) or res.logout(<optional redirect url>). The parameter for each function is optional and if not provided, the logInRedirect and logOutRedirect values from the options passed into the AuthorizationCodeFlow() function will be used.

Example:
app.get((req, res) => {
if (req.session.data.token == null ) {
res.login('/return_to_me_after_login')
}
})

This package also exposes two functions on your express instance: authenticate and autoAuthenticate. To require authentication for a route, just call the authenticate function at the beginning of the route handler. If you use the autoAuthenticate instead, the user will automatically be redirected to the signin route if they attempt to access a protected route without being logged in.

Index

Type Aliases

Functions