Search code examples
reactjsnext.jssingle-sign-onkeycloaknext-auth

Next-Auth keeps own session when Keycloak session logged out


I have a nextjs application with next-auth to manage the Keycloak authentication. Here is how I configured it

const keycloak = KeycloakProvider({
    clientId: process.env.KEYCLOAK_ID,
    clientSecret: process.env.KEYCLOAK_SECRET,
    issuer: process.env.KEYCLOAK_ISSUER,
});

export const authOptions: NextAuthOptions = {
    secret: process.env.NEXTAUTH_SECRET,
    providers: [
        keycloak
    ],
    callbacks: {
        jwt: async({ token, account }) => {/*Extra logic for sign-out keycloak session*/}
    },
    events: {
        signOut: async({ token }) => {/*Extra logic for sign-out keycloak session*/}
    },
}

I can successfully log-in and log-out (with some tweaks for keycloak).

The problem: When I drop Keycloak session from it's admin panel, Next-auth does not check that and keeps it's own session. Once API service tries to verify that token from Keycloak, verification fails because session was dropped. But Next-auth keeps own session as valid.

Any ideas how to force next-auth to check if Keycloak session is still valid or no?


Solution

  • I have found the solution to control this with tokens rotation

    https://authjs.dev/guides/basics/refresh-token-rotation

    One more link with the solution specific to Keycloak, just to check if anything goes wrong

    https://gist.github.com/degitgitagitya/db5c4385fc549f317eac64d8e5702f74

    I have also taken id_token when authenticated and reuse it when refresh token. id_token is needed to do Sign-out. I've used this solution, triggering additional keycloak sign-out in events:

    https://stackoverflow.com/a/75178127/7147231