@byu-oit-sdk/fastify
TypeScript icon, indicating that this package has built-in type declarations

0.8.1 • Public • Published

@byu-oit-sdk/fastify

Requirements:

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

Installing

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

npm install @byu-oit-sdk/fastify @byu-oit-sdk/session-dynamo

Introduction

Use this module to configure fastify 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 plugin configuration.

Options

In addition to the options below, any AuthorizationCodeProvider options may also be passed into the configuration.

Option 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 string - The client identifier issued to the client during the registration process.
clientSecret string - The client secret of the account being used.
redirectUri string - The redirection endpoint that the authorization server should redirect to after authenticating the resource owner.
discoveryEndpoint string - Used to configure where the user will be sent to sign in.

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.

Usage

JavaScript Coding Example
import { ByuLogger } from '@byu-oit/logger'
import { AuthorizationCodeFlow, byuOitGetIdToken as getIdToken } from '@byu-oit-sdk/fastify'
import fastifyCookie from '@fastify/cookie'
import { SessionPlugin } from '@byu-oit-sdk/session-fastify'
import Fastify from 'fastify'
import dynamoDbStoreFactory from 'connect-dynamodb'
import env from 'env-var'

/**
 * Environment variable setup.
 */
const secret = env.get('BYU_OIT_SIGNING_SECRET').required().asString()
const table = env.get('SESSION_TABLE').required().asString()
const isProduction = env.get('NODE_ENV').default('development').asEnum(['production', 'development']) === 'production'

/**
 * Initialize fastify with BYU Logger.
 */
export const fastify = Fastify({ logger: ByuLogger() })

/**
 * Must register the \@fastify/cookie plugin. The \@fastify/jwt module depends on \@fastify/cookie.
 */
await fastify.register(fastifyCookie)

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-fastify plugin. 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.
 */
await fastify.register(SessionPlugin, { store })

/**
 * AuthorizationCodeProvider options may be passed in the second parameter.
 */
await fastify.register(AuthorizationCodeFlow, { getIdToken })

/**
 * To require authentication for a route, just specify the authenticate function on the request object in the onRequest hook.
 */
fastify.get('/auth/user', { onRequest: [fastify.authenticate] }, (req, reply) => {
    return `Your CES UUID is ${req.session.user.cesUUID}`
})
TypeScript Coding Example
import { ByuLogger } from '@byu-oit/logger'
import { AuthorizationCodeFlow } from '@byu-oit-sdk/fastify'
import fastifyCookie from '@fastify/cookie'
import { SessionPlugin } from '@byu-oit-sdk/session-fastify'
import Fastify from 'fastify'
import env from 'env-var'
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/fastify' {
    interface UserInfo {
        /**
         * Declare your user info properties here
         */
    }
}

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

export const fastify = Fastify({ logger: ByuLogger() })

/**
 * Must register the \@fastify/cookie plugin. The \@fastify/jwt module depends on \@fastify/cookie.
 */
await fastify.register(fastifyCookie)

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

/**
 *  Must register the \@byu-oit-sdk/session-fastify plugin. 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.
 */
await fastify.register(SessionPlugin, { store })

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

await fastify.register(AuthorizationCodeFlow, {
    /**
     * 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 FastifyAuthorizationCodeProvider instance.
     */
    userInfoCallback (token) {
        if (typeof token.additional.id_token !== 'string') {
            /** The id token property must exist in the token response body */
            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)
    }
})

/**
 * To require authentication for a route, just specify the authenticate function on the request object in the onRequest hook.
 */
fastify.get('/auth/user', { onRequest: [fastify.authenticate] }, (req, reply) => {
    return req.session.user
})

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 fastify reply object in route handlers and such, so you can simply call reply.login(<optional redirect url>) or reply.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:
fastify.get((request, reply) => {
  if (req.session.data.token == null ) {
    reply.login('/return_to_me_after_login')
  }
})

This package also exposes two functions on your fastify instance: authenticate and autoAuthenticate. To require authentication for a route, just specify the authenticate function on the request object in the onRequest hook. 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.

/@byu-oit-sdk/fastify/

    Package Sidebar

    Install

    npm i @byu-oit-sdk/fastify

    Weekly Downloads

    4

    Version

    0.8.1

    License

    Apache-2.0

    Unpacked Size

    56 kB

    Total Files

    20

    Last publish

    Collaborators

    • byu-oit-bot
    • stuft2