Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Role Based Authorization in Auth0 and NextJS

I created a nextjs web application with Auth0.

A user can login and logout. I can reach also user information. But I cannot see user roles.

I am getting the profile with Auth0's getSession method.

I want to create 2 different pages in NextJS which are for user and admin roles.

So it will be basic API authorization that I want. If a user is in user role then the user can access only the user page. If a user has admin role then the user can access all pages.

To I achive this I need to get user roles.The getSession method does not return the user roles.

How can solve the problem?

Thanks

like image 339
tcetin Avatar asked Oct 15 '25 09:10

tcetin


1 Answers

I'm sure you've figured it out by now, but I had the same question.

You have to explicitly add the roles to your tokens (Auth and id) if you want them attached to the user object.

You can do this multiple ways but I did this by adding a rule in Auth0:

function setRolesToUser(user, context, callback) {
  const namespace = 'http://my-website-name.com';
  const assignedRoles = (context.authorization || {}).roles;

  let idTokenClaims = context.idToken || {};
  let accessTokenClaims = context.accessToken || {};

  idTokenClaims[`${namespace}/roles`] = assignedRoles;
  accessTokenClaims[`${namespace}/roles`] = assignedRoles;

  context.idToken = idTokenClaims;
  context.accessToken = accessTokenClaims;

  callback(null, user, context);
}

Now your token(s) will have the rule attached as a namespaced array w/ the assigned roles in said array.

Now that your tokens have the roles attached you can use it to gate content on Nextjs like this:

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

export async function getServerSideProps({ req, res }) {
 
  const session = getSession(req, res);
  if (!session?.user['http://my-website-name/roles'].includes('admin')) {
    return { props: { error: 'Forbidden' } };
  } else {
    return {
      props: {},
    };
  }
}

Then in your component, you can return early like so:

if (error) return <div>{error}</div>;

This explains server side but you can do similar client-side w/ useUser:

import { useUser} from '@auth0/nextjs-auth0';
like image 109
Optimus Prime Time Avatar answered Oct 17 '25 02:10

Optimus Prime Time



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!