Created
September 12, 2023 08:40
-
-
Save rafalkrupinski/85bbbfc8dabd0dce6fc5bcf1d93bb2be to your computer and use it in GitHub Desktop.
Get roles from Zitadel token with next-auth
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import NextAuth, {Profile} from "next-auth"; | |
import ZitadelProvider from "next-auth/providers/zitadel"; | |
import {CallbacksOptions} from "next-auth/src/core/types"; | |
const ZITADEL_PROJECT_ID = process.env.ZITADEL_PROJECT_ID!; | |
type ProjectURN = string; | |
type AllProjectsURN = 'urn:zitadel:iam:org:project:roles'; | |
type RoleKey = string; | |
type OrganizationId = string; | |
type OrganizationDomain = string; | |
type ZitadelProfile = Profile & Record< | |
ProjectURN | AllProjectsURN, | |
Record< | |
RoleKey, | |
Record< | |
OrganizationId, | |
OrganizationDomain | |
> | |
> | |
>; | |
const ALL_PROJECT_URN: AllProjectsURN = 'urn:zitadel:iam:org:project:roles'; | |
/** | |
* Extracts the roles associated with a specific project and organization from a Zitadel profile. | |
* | |
* @param {ZitadelProfile} profile - The Zitadel profile containing the roles. | |
* @param {OrganizationId} orgId - The ID of the organization. | |
* @return {string[]} An array of roles associated with the project and organization. | |
*/ | |
function extractRoles(profile: ZitadelProfile, orgId: OrganizationId): string[] { | |
const roles = profile[ALL_PROJECT_URN] | |
return Object.keys(roles).filter(roleKey => orgId in roles[roleKey]) | |
} | |
const handler = NextAuth({ | |
providers: [ | |
ZitadelProvider({ | |
issuer: process.env.ZITADEL_ISSUER, | |
clientId: process.env.ZITADEL_CLIENT_ID!, | |
clientSecret: process.env.ZITADEL_CLIENT_SECRET!, | |
}),], | |
callbacks: { | |
async session(params: Parameters<CallbacksOptions['session']>[0]) { | |
console.log('session', params) | |
const {session, token} = params; | |
return { | |
...session, | |
roles: token.roles, | |
} | |
}, | |
async jwt(params: Parameters<CallbacksOptions['jwt']>[0]) { | |
const {token, profile} = params; | |
const zitadelProfile = profile as ZitadelProfile | undefined; | |
return { | |
...token, | |
roles: token.roles ?? (zitadelProfile ? extractRoles(zitadelProfile, ZITADEL_PROJECT_ID) : undefined), | |
}; | |
} | |
} | |
}); | |
export {handler as GET, handler as POST} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment