Redirection of users based on roles

I am trying to do this based on actions → flows

/**
 * @param {Event} event - Details about the user and the context in which they are logging in.
 * @param {PostLoginAPI} api - Interface whose methods can be used to change the behavior of the login.
 */
exports.onExecutePostLogin = async (event, api) => {
  const namespace = 'https://api';
  if (event.authorization) {
    api.idToken.setCustomClaim(`${namespace}/roles`, event.authorization.roles);
    api.accessToken.setCustomClaim(`${namespace}/roles`, event.authorization.roles);

    const token = api.redirect.encodeToken({
    secret: event.secrets.MY_REDIRECT_SECRET,
    expiresInSeconds: 60, 
    payload: {
      // Custom claims to be added to the token
      email: event.user.email,
    },
    });
    if (event.authorization.roles.includes("Admin")) {
      api.redirect.sendUserTo("http://localhost:8910/admin", {
      query: { session_token: token }
    });
    }
  }
}

For some odd reason the page now goes straight back to the main page without login in.

Hi @goossensb.bart,

Welcome to the Auth0 Community!

The redirect from Actions is intended for redirect during authentication, not after. You must redirect back to an action to complete the flow.

If you want to redirect after authentication, you should do so in your application. You can add the roles to the token and redirect in your application after you get the tokens.

1 Like