KINDERAS.COM

Sun Aug 28 2022

Implementing federated sign out when using next-auth in you Next.js app

When using federated auth, such a Google or a custom oAuth & OpenId Connect setup, a user will in some cases expect to be signed out from the original provider as well as your Next application. In this post I'll go into detail on how this can be achieved using next-auth v4.

Next-auth will as writing this (v4.10) not automatically handle federated sign out defined by the OpenId standard, so we have to manually implement this.

This post is based on this Github discussion over at the next-auth repo. See sources below.

The approach

  1. When the user clicks the logout button, redirect the user to a custom /auth/federated-sign-out route.
  2. After the thrid party provider has signed the user out, the federated auth server will redirect back to a route in the Next app (e.g. `/logout`). This page/route is passed to the provider auth server using the post_logout_redirect_uri parameter defined by the OpenID standard.

We'll need two new routes and a sign out button component. We will also need access to the original id token provided by the federated provider, let's take a look at this first.

How the get the provider id token

Since next-auth creates its own token, it doesn't automatically give you access to the original id token from the third party provider.

However, it's quite straight forward to make the original id token available in the next-auth created token. We'll need to update the pages/api/auth/[...nextauth].ts route to make this happen.

The /logout route/component

The logout route will sign the user out locally, meaning that the next-auth session will be removed and the user will be signed out from both the federated provider auth server and your Next.js application.

This route is a simple React component which will automatically call the next-auth signOut function (without a redirect), then redirect to the root page (or a page of your choosing).

PS: You can place this page/route where ever you want to, as long as the path matches the post_logout_redirect_uri defined in the /auth/federated-sign-out route.

The sign out button

The sign out button will redirect the user to the /auth/federated-sign-out route (see below). You can e.g define this button as a React component like so.

The `/auth/federated-sign-out` route

This route will assemble the provider /connect/endsession url, including query params (original id token and url to the logout page), and then redirect the user to the provider auth server.

PS: For this to work properly you'll probably need to configure valid redirect url's at the provider OpenID setup.

And that's it.

Sources