0

I'm using NextAuth with the Prisma adapter and AWS Cognito and it works perfectly, but my problem is that my User model doesn't get updated if I change the groups on Cognito. This is how I configured NextAuth:

// I copied the original and changed some of the fields
export type CognitoProfile = {
    email: string;
    sub: string;
    preferred_username: string;
    "cognito:groups": string[];
};

const CognitoProvider = (
    options: OAuthUserConfig<CognitoProfile>
): OAuthConfig<CognitoProfile> => {
    return {
        id: "cognito",
        name: "Cognito",
        type: "oauth",
        wellKnown: `${options.issuer}/.well-known/openid-configuration`,
        idToken: true,
        profile: (profile) => {
            return {
                id: profile.sub,
                name: profile.preferred_username,
                email: profile.email,
                image: "",
                roles: profile["cognito:groups"],
            };
        },
        options,
    };
};

export const authOptions: NextAuthOptions = {
    // Include user.id on session
    callbacks: {
        session: ({ session, user }) => {
            console.log(`User: ${JSON.stringify(user)}`);
            if (session.user) {
                session.user.id = user.id;
            }
            return session;
        },
    },
    adapter: PrismaAdapter(prisma),
    providers: [
        CognitoProvider({
            clientId: process.env.COGNITO_CLIENT_ID!,
            clientSecret: process.env.COGNITO_CLIENT_SECRET!,
            issuer: process.env.COGNITO_ISSUER,
        }),
    ],
};

This works perfectly when a new user logs in (their groups are saved properly).

The problem is that the database is not updated when I log out and log back in after I add/remove group(s) to a Cognito user. This problem is not Cognito-specific it would be the same with things like Keycloak.

I checked the NextAuth docs, but I didn't find a solution for this. What's the recommended way of keeping the User model up to date? I don't want to reinvent the wheel

Adam Arold
  • 29,285
  • 22
  • 112
  • 207

0 Answers0