I have been trying to implement RBAC to my application.
I have an API and a Frontend, the APi has access to the management API but the frontend is a typical NextJs application.
I am trying to get the currently logged in users role in the middleware through the getSession() hook.
I have added the roles to the accesstoken and the idtoken, when I log in and console log those values the roles have indeed been added to the tokens correctly. So I have set the action correctly and everything.
What I don’t get is why can’t I access it in the user object? Am I supposed to parse the jwt token myself?
I’m not sure what is left to check.
- Created the roles and added them to my user.
- Created a action and assign it to post-login trigger via auth0 dashboard.
- Initialize the auth0 sdk within nextjs:
import { Auth0Client } from "@auth0/nextjs-auth0/server"
export const auth0 = new Auth0Client({
authorizationParameters: {
audience: process.env.AUTH0_AUDIENCE,
scope: 'openid profile email roles'
},
})
- note that the audience comes from the same api which I’m using for my server.
- Create the middleware and fetch the roles for the user.
import {NextRequest, NextResponse} from "next/server"
import { auth0 } from "./lib/auth0"
export async function middleware(request: NextRequest) {
const authRes = await auth0.middleware(request)
if (request.nextUrl.pathname.startsWith("/auth")) {
return authRes
}
const session = await auth0.getSession()
if (!session){
return NextResponse.redirect(new URL("/auth/login", request.nextUrl.origin))
} else {
const roles: string[] = session?.user['https://your-app-name.com/roles'];
console.log(roles)
console.log(session.user)
console.log(session.tokenSet.accessToken)
}
}
Am I missing something crucial in the flow?