ASP.NET Core v2.0: Authorization

View on Github

ASP.NET Core v2.0: Authorization

Gravatar for andres.aguiar@auth0.com
By Andres Aguiar
Auth0

This tutorial will show you how assign roles to your users, and use those claims to authorize or deny a user to access certain routes in the app. We recommend you to Log in to follow this quickstart with examples configured for your account.

Or

I want to explore a sample app

2 minutes

Get a sample configured with your account settings or check it on Github.

View on Github
System requirements: .NET Core SDK 2.1.300 | .NET Core 2.1.0 | ASP.NET Core 2.1.0 | Visual Studio 2017 15.7 or Visual Studio Code (Optional)

ASP.NET Core supports Role based Authorization which allows you to limit access to your application based on the user's role. This tutorial shows how to add role information to the user's ID token and then use it to limit access to your application.

To follow the tutorial, make sure you are familiar with Rules.

Create a Rule to Assign Roles

Create a rule that assigns the following access roles to your user:

  • An admin role
  • A regular user role

To assign roles, go to the New rule page. In the Access Control section, create an empty rule.

Use the following code for your rule:

function (user, context, callback) {
  var addRolesToUser = function(user, cb) {
    if (user.email.indexOf('@example.com') > -1) {
      cb(null, ['admin']);
    } else {
      cb(null, ['user']);
    }
  };

  addRolesToUser(user, function(err, roles) {
    if (err) {
      callback(err);
    } else {
      context.idToken["https://schemas.quickstarts.com/roles"] = roles;     
      callback(null, user, context);
    }
  });
}

Update the code to check for your own email domain, or match your custom condition.

You can define more roles other than admin and user, or customize the whole rule, depending on your product requirements.

This quickstart guide uses https://schemas.quickstarts.com for the claim namespace. We recommend that you use a namespace related to your own Auth0 tenant for your claims, for example, https://schemas.YOUR_TENANT_NAME.com.

For more information on custom claims, read User profile claims and scope.

Restrict Access Based on User Roles

Configure the OIDC authentication handler registration inside your ASP.NET application to inform it which claim in the ID Token contains the role information. Specify the RoleClaimType inside TokenValidationParameters. The value you specify must match the namespace you used in your rule.

public void ConfigureServices(IServiceCollection services)
{
    // Some code omitted for brevity...

    // Add authentication services
    services.AddAuthentication(options => {
        options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    })
    .AddCookie())
    .AddOpenIdConnect("Auth0", options => {
        // ...

        // Configure the scope
        options.Scope.Clear();
        options.Scope.Add("openid");
        options.Scope.Add("profile");
        options.Scope.Add("email");

        // Set the correct name claim type
        options.TokenValidationParameters = new TokenValidationParameters
        {
            NameClaimType = "name",
            RoleClaimType = "https://schemas.quickstarts.com/roles"
        };

        options.Events = new OpenIdConnectEvents
        {
            // handle the logout redirection 
            OnRedirectToIdentityProviderForSignOut = (context) =>
            {
                // ...
            }
        };   
    });
}

You can use the Role based authorization mechanism to make sure that only the users with specific roles can access certain actions. Add the [Authorize(Roles = ?)] attribute to your controller action.

The sample code below restricts the action only to users who have the admin role:

// Controllers/HomeController.cs

[Authorize(Roles = "admin")]
public IActionResult Admin()
{
  return View();
}
Use Auth0 for FREE