How to see users role in react frontend

Hello, i would like to see whic role a user has, for then showing things in react only if a certain role is enabled for that user.

like this
`if (user.role1) {

return (
  <React.Fragment>
    <h1>The role 1 is enabled</h1>
  </React.Fragment>
)

};`

i tried with the managment api to get roles but that doesn’t work and is not good to call api managment from single page applications, i tried to add roles to metadata but i don’t know how to acces those roles,

somone can help me?

SOLVED
i added a rule in the auth0 library like this

exports.onExecutePostLogin = async (event, api) => {
  const namespace = 'https://myroles.com';
  if (event.authorization) {
    api.idToken.setCustomClaim(`${namespace}/roles`, event.authorization.roles);
    api.accessToken.setCustomClaim(`${namespace}/roles`, event.authorization.roles);
  }
}

then in react you can view it in the user from useAuth0() hook:

import './App.css';
import './Loader.css';
import React, {  } from 'react';
import LoginButton from './Components/Login/Login';
import LogoutButton from './Components/Login/Logout';
import { useAuth0 } from "@auth0/auth0-react";
import MainHeader from './Components/MainHeader/MainHeader';
 

function App() {

  const { user, isAuthenticated, isLoading } = useAuth0();

  if (isLoading) {
    return (
      <React.Fragment>
        <br/>
        <div className="lds-roller"><div></div><div></div><div></div><div></div><div></div><div></div><div></div><div></div></div>
      </React.Fragment>
    );
  } 
  else if (!isAuthenticated) {
    return (
      <React.Fragment>
        <MainHeader />
        <h1>Please login!</h1>
        <LoginButton />
      </React.Fragment>
    )
  } 
  else if (isAuthenticated) {
    // <GetRole id={user.sub}/>
    // GetRoleP(user.sub);
    const roles = user['https://myroles.com/roles'];
    let nsIsEnabled = roles.includes('nos-security');

    if (nsIsEnabled){
      return (
        <React.Fragment>
          <MainHeader />
          <h1>Welcome {user.name}</h1>
          <h1>Nos security enabled</h1>
          <LogoutButton />
        </React.Fragment>
      )
    } else {
      return (
        <React.Fragment>
          <MainHeader />
          <h1>Welcome {user.name}</h1>
          <LogoutButton />
        </React.Fragment>
      )
    };
  };
}

export default App;
2 Likes

Hey there @fornitori welcome to the community and thanks a bunch for following up with your solution :rocket:

Minor detail: For anyone looking at the extensibility bit to add roles to tokens, this is actually an Action.

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