@byu-oit-sdk/express v0.6.2
@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
function into the middleware configuration.
Signing In
- For a user to log in, the browser should direct the user to the
logIn
route. - 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 thelogInRedirect
option passed into the configuration. - 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
- For a user to log out, the browser should direct the user to the
logOut
route. - When the user logs out, their session is cleared but the token is not revoked.
- After logging out, they will be redirected to the
logOutRedirect
route. - 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 | /auth/signin | The path which redirects the caller to the authorization url to sign in. |
logInRedirect | - | string | /auth/user | The path to redirect the caller to after signing in. |
logOut | - | string | /auth/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. |
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.
import { AuthorizationCodeFlow } from '@byu-oit-sdk/express'
const app = Express()
// ... add middleware to app
const options = {
logIn: 'myRoute/myLoginEndpoint'
}
AuthorizationCodeFlow(app, options)
// ... add middleware to app
// run the app
import { AuthorizationCodeFlow, AuthorizationCodePluginOptions } from '@byu-oit-sdk/express'
const app = Express()
// ... add middleware to app
const options: AuthorizationCodePluginOptions = {
logIn: 'myRoute/myLoginEndpoint'
}
AuthorizationCodeFlow(app, options)
// ... 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
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!')
})
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 /auth/signin
and /auth/signout
, respectively). The user could even manually navigate to those routes in their browser.
<a href="/auth/signout">Sign Out</a>
<a href="/auth/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.
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.
7 days ago
2 months ago
2 months ago
2 months ago
3 months ago
3 months ago
4 months ago
4 months ago
4 months ago
4 months ago
4 months ago
9 months ago
8 months ago
9 months ago
8 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
9 months ago
8 months ago
8 months ago
11 months ago
11 months ago
10 months ago
7 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago
11 months ago