How to implement custom authentication in auth0 and hasura graphql?

Viewed 611

I am working on a reservation application. Currently, we use auth0 for authentication in Flutter and Hasura graphql as our db. Our system has two apps: one for users and one for managers. The User's app can both Sign Up and Sign In, but in the Manager's app only for Sign In, where the manager user is registered by Administrator. In the Manager's app, we have multiple roles such as staff, manager, owner,... In the User's app, we have only a user role.

In Auth0 we can create "rule" to assign a user role when user signUp/signIn as follows.

function (user, context, callback) {
  const namespace = "https://hasura.io/jwt/claims";
  context.idToken[namespace] = 
    { 
      'x-hasura-default-role': 'user',
      'x-hasura-allowed-roles': ['user'],
      'x-hasura-user-id': user.user_id
    };
  callback(null, user, context);
}

this rule run in all the applications we created in Auth0. So, when we create a manager user. The role is set to the user role. My question is, I want to create a manager user in manager app, how can I assign a specific role for each user. For example, Admin can create a user with a staff role...

1 Answers

Admins can create users from the Manager's app - I assume they might specify attributes like name, email, etc.

They may hit a Custom Action or Remote Schema field (with appropriate permissions and login credentials), that makes an authenticated outbound request to create the user in Auth0 (POST /api/v2/users) and then update the reference record in Hasura DB with the auth0 id. In Hasura you can also store the role along with email, name, etc.

Now after the user has signed up (set their password), they sign in to trigger the custom rule.

Following this documentation, as you have, replace

// do some custom logic to decide allowed roles

With some logic that makes a request to your Hasura endpoint and gets the role information and any other data based on the user email attempting to login. This user-specific data can then be used to construct the JWT. You can hit Hasura from the Auth0 Rule via HASURA_GRAPHQL_ADMIN_SECRET stored in Rule Settings. E.g.

const adminSecret = configuration.HASURA_GRAPHQL_ADMIN_SECRET

If you want login to work in multiple environments (esp. local), I think you'll need to (a) expose your local hasura to the internet via something like ngrok and (2) pass in custom params into the rule to control its behavior, specifically which Hasura endpoint it's hitting.

In Auth0 Context object, you can pass any data via query params during login. For example:

const hasuraEndpoint = context.request.query.hasuraEndpoint

can be used in the Rule vs. a statically defined endpoint.

Related