1.0.2 • Published 5 months ago

@auth0/auth0-fastify v1.0.2

Weekly downloads
-
License
MIT
Repository
github
Last release
5 months ago

The Auth0 Fastify SDK is a library for implementing user authentication in Fastify applications.

Release Downloads License

šŸ“š Documentation - šŸš€ Getting Started - šŸ’¬ Feedback

Documentation

  • Examples - examples for your different use cases.
  • Docs Site - explore our docs site and learn more about Auth0.

Getting Started

1. Install the SDK

npm i @auth0/auth0-fastify

This library requires Node.js 20 LTS and newer LTS versions.

2. Register the Auth0 Fastify plugin

Register the Auth0 fastify plugin with the Fastify instance.

import auth0 from '@auth0/auth0-fastify';

fastify.register(auth0, {
  domain: '<AUTH0_DOMAIN>',
  clientId: '<AUTH0_CLIENT_ID>',
  clientSecret: '<AUTH0_CLIENT_SECRET>',
  appBaseUrl: '<APP_BASE_URL>',
  sessionSecret: '<SESSION_SECRET>'
});

The AUTH0_DOMAIN, AUTH0_CLIENT_ID, and AUTH0_CLIENT_SECRET can be obtained from the Auth0 Dashboard once you've created an application. This application must be a Regular Web Application.

The SESSION_SECRET is the key used to encrypt the session cookie. You can generate a secret using openssl:

openssl rand -hex 64

The APP_BASE_URL is the URL that your application is running on. When developing locally, this is most commonly http://localhost:3000.

!IMPORTANT
You will need to register the following URLs in your Auth0 Application via the Auth0 Dashboard:

  • Add http://localhost:3000/auth/callback to the list of Allowed Callback URLs
  • Add http://localhost:3000 to the list of Allowed Logout URLs

Routes

The SDK for Fastify Web Applications mounts 4 main routes:

  1. /auth/login: the login route that the user will be redirected to to initiate an authentication transaction. Supports adding a returnTo querystring parameter to return to a specific URL after login.
  2. /auth/logout: the logout route that must be added to your Auth0 application's Allowed Logout URLs
  3. /auth/callback: the callback route that must be added to your Auth0 application's Allowed Callback URLs
  4. /auth/backchannel-logout: the route that will receive a logout_token when a configured Back-Channel Logout initiator occurs

To disable this behavior, you can set the mountRoutes option to false (it's true by default):

fastify.register(auth0, {
  mountRoutes: false
});

Additionally, by setting mountConnectRoutes to true (it's false by default) the SDK also can also mount 4 routes useful for account-linking:

  1. /auth/connect: the route that the user will be redirected to to initiate account linking
  2. /auth/connect/callback: the callback route for account linking that must be added to your Auth0 application's Allowed Callback URLs
  3. /auth/unconnect: the route that the user will be redirected to to initiate account linking
  4. /auth/unconnect/callback: the callback route for account linking that must be added to your Auth0 application's Allowed Callback URLs

!IMPORTANT
When mountRoutes is set to false, setting mountConnectRoutes has no effect.

3. Adding Login and Logout

When using the built-in mounted routes, the user can be redirected to /auth/login to initiate the login flow and /auth/logout to log out.

<a href="/auth/logout">Log out</a>
<a href="/auth/login">Log in</a
>

When not using the built-in routes, you want to call the SDK's startInteractiveLogin(), completeInteractiveLogin() and logout() methods:

fastify.get('/custom/login', async (request, reply) => {
  const authorizationUrl = await fastify.auth0Client.startInteractiveLogin(
    {
      authorizationParams: {
        // Custom URL to redirect back to after login to handle the callback.
        // Make sure to configure the URL in the Auth0 Dashboard as an Allowed Callback URL.
        redirect_uri: 'http://localhost:3000/custom/callback',
      }
    },
    { request, reply }
  );

  reply.redirect(authorizationUrl.href);
});


fastify.get('/custom/callback', async (request, reply) => {
  await fastify.auth0Client.completeInteractiveLogin(
    new URL(request.url, options.appBaseUrl),
    { request, reply }
  );

  reply.redirect('https://localhost:3000');
});

fastify.get('/custom/logout', async (request, reply) => {
  const logoutUrl = await auth0Client.logout({ returnTo: 'https://localhost:3000' }, { request, reply });

  reply.redirect(logoutUrl.href);
});

4. Protecting Routes

In order to protect a Fastify route, you can use the SDK's getSession() method in a custom preHandler:

async function hasSessionPreHandler(request: FastifyRequest, reply: FastifyReply) {
  const session = await fastify.auth0Client!.getSession({ request, reply });

  if (!session) {
    reply.redirect('/auth/login');
  }
}

fastify.get(
  '/profile',
  {
    preHandler: hasSessionPreHandler,
  },
  async (request, reply) => {
    const user = await fastify.auth0Client!.getUser({ request, reply });

    return reply.viewAsync('profile.ejs', {
      name: user!.name,
    });
  }
);

!IMPORTANT
The above is to protect server-side rendering routes by the means of a session, and not API routes using a bearer token.

Requesting an Access Token to call an API

If you need to call an API on behalf of the user, you want to specify the audience parameter when registering the plugin. This will make the SDK request an access token for the specified audience when the user logs in.

fastify.register(fastifyAuth0, {
  domain: '<AUTH0_DOMAIN>',
  clientId: '<AUTH0_CLIENT_ID>',
  clientSecret: '<AUTH0_CLIENT_SECRET>',
  audience: '<AUTH0_AUDIENCE>',
  appBaseUrl: '<APP_BASE_URL>',
  sessionSecret: '<SESSION_SECRET>',
});

The AUTH0_AUDIENCE is the identifier of the API you want to call. You can find this in the API section of the Auth0 dashboard.

Retrieving the token can be achieved by using getAccessToken:

const accessTokenResult = await fastify.auth0Client.getAccessToken({ request, reply });
console.log(accessTokenResult.accessToken);

Feedback

Contributing

We appreciate feedback and contribution to this repo! Before you get started, please read the following:

Raise an issue

To provide feedback or report a bug, please raise an issue on our issue tracker.

Vulnerability Reporting

Please do not report security vulnerabilities on the public GitHub issue tracker. The Responsible Disclosure Program details the procedure for disclosing security issues.

What is Auth0?

1.0.2

5 months ago

1.0.1

7 months ago

1.0.0

7 months ago