DEV Community

Cover image for Securing ASP.NET Core MVC 6 App - Add roles - Part 3
Emanuele Bartolesi
Emanuele Bartolesi

Posted on

Securing ASP.NET Core MVC 6 App - Add roles - Part 3

In the previous two articles of this series, we have learned how to add the authentication to an ASP.NET Core MVC 6 based on Auth0 and how to display a profile page.
In this post, we will add the roles to the users, and we will deny or allow access to views.

Create and assign a role

First of all, we need to create a new role in the Auth0 Dashboard.
Navigate to "User Management" -> "Roles".
Click on the button at the top of the page, called "Create Role".

Insert the name of the role and a description.

Admin Role

In our example, we are using the name "Administrator".

From the Users list (in the User Management menu), click on a user and click on the tab "Roles".
And then, click on the button "Assign roles".

Assign roles

Select the role that you want to assign to the user.
In our case "Administrator".

Add Rules to Auth0

Now we need to add the role to the authorization token.
In order to do that, we need to create a new rule from the menu "Auth Pipeline" -> "Rules".
Create an empty rule and paste the code below.

function (user, context, callback) {
  const assignedRoles = (context.authorization || {}).roles;
  const idTokenClaims = context.idToken || {};

idTokenClaims['http://schemas.microsoft.com/ws/2008/06/identity/claims/role'] = assignedRoles;

  context.idToken = idTokenClaims;

  callback(null, user, context);
}
Enter fullscreen mode Exit fullscreen mode

Now we are ready to come back to the code in our project.

Add roles to the ASP.NET MVC 6 Project

If you followed the previous steps in the other two posts, you don't need to change the existing code, but we need to add the roles management in a Controller.
For instance we want to deny the access to the page "Privacy" if the user is not an administrator.

Open the "HomeController.cs" file and replace the code of the action Privacy with the code below.

[Authorize(Roles = "Administrator")] 
public IActionResult Privacy()
{
    return View();
}
Enter fullscreen mode Exit fullscreen mode

In this example only a user with at least the role "Administrator" can access to this page.

Conclusion

In this short series we have learned how to implement a basic authentication flow with Auth0.
As you can see it's very easy but at the same time Auth0 offers a complete implementation for your next project in terms of security and productivity.

If you want to try Auth0, you can follow this link to create your own account and start to use it in your next project!

Discussion (1)

Collapse
berviantoleo profile image
Bervianto Leo Pratama

Cool. Thanks for sharing. πŸ‘