Proper way to check for roles/permissions on nextjs backend

Hello,

In my application, I have a set of roles and permissions, which I added to my identity token claims using custom flows. These are used to hide/show UI elements. I am using NextJS and the auth0-nextjs SDK.

I am not sure what is the proper way of checking authorization on the backend. Of course I have the withApiAuthRequired wrapper for the functions, but I am not sure how should I check if a user has a specific permission. Is there a simpler way of doing that instead of doing an API call to the ManagementAPI? Can I use the accessToken somehow? It does not seem to be a JWT.

Thanks!

Hi @faabiopk,

Thanks for reaching out to the Auth0 Community!

I understand you need help getting the user Roles/Permissions on your Next.js app.

I recommend using the getSession method to get the Roles/Permissions in the custom claim from the ID Token. For example:

import { getSession } from '@auth0/nextjs-auth0';

// pages/admin.js
export default function Admin({ error }) => error ? <div>error<div> : <div>Admin Section</div>;

export getServerSideProps = ({ req, res }) => {
  const session = getSession(req, res);
  if (!session?.user['http://your-namespace/roles'].includes('admin')) {
    return { props: { error: 'Forbidden' } }
  }
}

I hope this helps!

Please let me know how this goes for you.

Thanks,
Rueben

Hi Rueben!

Yes, I need help, but in the backend instead. I was able to use the roles/permissions on the frontend without problems.

I am not sure how to use them on the backend of NextJS, could you point me to the direction? This information is on the ID token, right? On the backend I should NOT use it for authorization, correct?

Thank you

Hi @faabiopk,

Thank you for your response.

For the backend, I recommend using the Management API’s Get a user’s roles and Get a User’s Permissions endpoints.

Reference docs:

And to reiterate, you could append the user’s Roles and Permissions as custom claims in the Access Token. Please make sure to include the audience parameter when requesting an access token for it to be a JWT. See this doc for details.

Thanks,
Rueben

2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.