After a user logs in, I’m trying to redirect admin users to a certain page whereas non-admin users should be redirected to a different page.
I have the current user’s role stored in the session object in /api/auth/handleCallback but it seems that the handleLogin method does not have the session parameter. I’m aware that we can change the returnTo property in the return value of handleLogin but how could I conditionally set the redirect URL based on the user role?
I ended up going with redirect after successful authentication.
We set up custom claims using the Actions flow to attach roles to the idToken. When a user logins, they’re authenticated and redirected back to the root URL /. Using SSR, we’re checking the roles on the session in this landing page and doing a server-side redirect.
Thanks for your answer.
What do you mean by custom claims?
Once logged in, how do you retrieve the user’s role, and then redirect accordingly?
Or is this landing page a “dummy” page, just for you to see the roles and take actions depending? How do you achieve this?
But i’m still fairly new… could you share a bit more about what you mean?
Basically, we have a post-login action that attaches roles to the idToken of the user who logged in. Though there are probably other ways you could go about adding roles / custom claims to the idToken of the user.
By setting a custom claim on the idToken of a user, you can access these claims in the session of an authenticated user. A bit more contrived example:
User lands on root URL https://my-app/ and goes through login flow
Upon successful authentication, user is redirected back to root URL https://my-app/
Using getServerSideProps in this root URL page, we are using getSession from the auth0/next-js SDK to check the custom claim.
Depending on the role that we checked in their session and that is available from setting the custom claims prior, we are redirecting from getServerSideProps to a different page.
The landing page is not a “dummy” page - it’s the page that hosts our login buttons and takes you through the Auth0 login flow. The user is redirected back here after successful authentication, but at this point they have a session so we can check their custom claims.
Basically the key is setting the user’s roles as custom claims in a separate flow (actions, rules, etc) and being able to check this role once they are authenticated. The rest is just Next.js.
Thanks so much for the details. I think I’m getting closer to understanding.
How do you direct to another page exactly from the getServerSideProps you’re mentioning?
I’m able to extract the details of the session including the user and its role attached, but not sure how to redirect conditionally based on his role now.