ASP.NET Core Web API Authorization

Version: v1.1

Sample Project

Download a sample project specific to this tutorial configured with your Auth0 API Keys.

System Requirements
  • .NET Core 1.1
  • ASP.NET Core 1.1
  • Microsoft.AspNetCore.Authentication.JwtBearer 1.1.1
  • Visual Studio 2017 (Optional)
  • Visual Studio Code (Optional)
Show requirements

At some point, your APIs may need to allow limited access to users, servers, or servers on behalf of users. This tutorial demonstrates how to use the OAuth 2.0 authorization features of Auth0 to give your applications (or third-party applications) limited access to your APIs on behalf of users. For more information, check out our documentation.

This Quickstart will guide you through the various tasks related to using Auth0-issued Access Tokens to secure your ASP.NET Core Web API.

Seed and Samples

If you would like to follow along with this Quickstart you can download the seed project. The seed project is just a basic ASP.NET Web API with a simple controller and some of the NuGet packages which will be needed included. It also contains an appSettings.json file where you can configure the various Auth0-related settings for your application.

The final project after each of the steps is also available in the Quickstart folder of the Samples repository. You can find the final result for each step in the relevant folder inside the repository.

Create a Resource Server (API)

In the APIs section of the Auth0 Dashboard, click the Create API button. Provide a Name and Identifier for your API. The identifier you set will later be used as the audience when configuring access_token verification. Be sure to choose the RS256 signing algorithm.

Create API

Also, update the appsettings.json file in your project with the correct Domain and API Identifier for your API, e.g.

{
  "Auth0": {
    "Domain": "YOUR_AUTH0_DOMAIN",
    "ApiIdentifier": "{YOUR_API_IDENTIFIER}"
  }
}

Add API Authorization

To restrict access to the resources served by your API, a check needs to be made to determine whether the incoming request contains valid authorization information. There are various methods for including authorization information in a request, but for integration with Auth0, your API needs to check for a valid JSON Web Token (JWT). When users log into your application, they will receive an id_token and an access_token which are both JWTs. The specific JWT that needs to be sent to your API is the access_token.

This sample demonstrates how to check for a JWT in the Authorization header of an incoming HTTP request and verify that it is valid using the standard ASP.NET Core JWT middleware.

Install Dependencies

To use Auth0 Access Tokens with ASP.NET Core you will use the JWT Middleware. Add the Microsoft.AspNetCore.Authentication.JwtBearer package to your application.

Install-Package Microsoft.AspNetCore.Authentication.JwtBearer

Configuration

By default, your API will be set up to use RS256 as the algorithm for signing tokens. Since RS256 works by using a private/public keypair, tokens can be verified against the public key for your Auth0 account. This public key is accessible at https://YOUR_AUTH0_DOMAIN/.well-known/jwks.json.

It is highly recommended that you use the default signing algorithm of RS256 for your API. If you do require HS256 as the algorithm, see the HS256 integration sample.

The ASP.NET Core JWT middleware will handle downloading the JSON Web Key Set (JWKS) file containing the public key for you, and will use that to verify the access_token signature.

To add the JWT middleware to your application's middleware pipeline, go to the Configure method of your Startup class and add a call to UseJwtBearerAuthentication passing in the configured JwtBearerOptions. The JwtBearerOptions needs to specify your Auth0 API Identifier as the Audience, and the full path to your Auth0 domain as the Authority:

// Startup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    var options = new JwtBearerOptions
    {
        Audience = Configuration["Auth0:ApiIdentifier"],
        Authority = $"https://{Configuration["Auth0:Domain"]}/"
    };
    app.UseJwtBearerAuthentication(options);

    app.UseMvc();
}

The JWT middleware integrates with the standard ASP.NET Core Authentication and Authorization mechanisms. To secure an endpoint you only need to decorate your controller action with the [Authorize] attribute:

// Controllers/PingController.cs

[Route("api")]
public class PingController : Controller
{
    [Authorize]
    [HttpGet]
    [Route("ping/secure")]
    public string PingSecured()
    {
        return "All good. You only get this message if you are authenticated.";
    }
}

Configuring Scopes

The JWT middleware above verifies that the access_token included in the request is valid; however, it doesn't yet include any mechanism for checking that the token has the sufficient scope to access the requested resources.

Scopes provide a way for you to define which resources should be accessible by the user holding a given access_token. For example, you might choose to permit read access to a messages resource if a user has a manager access level, or a create access to that resource if they are an administrator.

To configure scopes in your Auth0 dashboard, navigate to your API and select the Scopes tab. In this area you can define any scopes you wish. For this sample you can define ones called read:messages and create:messages.

To ensure that an access_token contains the correct scope you can make use of the Policy-Based Authorization in ASP.NET Core.

For a better understanding of the code which follows, it is suggested that you read the ASP.NET Core documentation on Policy-Based Authorization.

Create a new Authorization Requirement called HasScopeRequirement. This requirement will check that the scope claim issued by your Auth0 tenant is present, and if so it will ensure that the scope claim contains the requested scope. If it does then the Authorization Requirement is met.

// HasScopeRequirement.cs

public class HasScopeRequirement : AuthorizationHandler<HasScopeRequirement>, IAuthorizationRequirement
{
    private readonly string issuer;
    private readonly string scope;

    public HasScopeRequirement(string scope, string issuer)
    {
        this.scope = scope;
        this.issuer = issuer;
    }

    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, HasScopeRequirement requirement)
    {
        // If user does not have the scope claim, get out of here
        if (!context.User.HasClaim(c => c.Type == "scope" && c.Issuer == issuer))
            return Task.CompletedTask;

        // Split the scopes string into an array
        var scopes = context.User.FindFirst(c => c.Type == "scope" && c.Issuer == issuer).Value.Split(' ');

        // Succeed if the scope array contains the required scope
        if (scopes.Any(s => s == scope))
            context.Succeed(requirement);

        return Task.CompletedTask;
    }
}

Next, you can define a policy for each of the scopes in your application in the ConfigureServices method of your Startup class:

// Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    // Add framework services.
    services.AddMvc();

    string domain = $"https://{Configuration["Auth0:Domain"]}/";
    services.AddAuthorization(options =>
    {
        options.AddPolicy("read:messages",
            policy => policy.Requirements.Add(new HasScopeRequirement("read:messages", domain)));
        options.AddPolicy("create:messages",
            policy => policy.Requirements.Add(new HasScopeRequirement("create:messages", domain)));
    });
}

Finally, to ensure that a scope is present in order to call a particular API endpoint, you simply need to decorate the action with the Authorize attribute, and pass the name of the Policy for that scope in the policy parameter:

// Controllers/MessagesController.cs

[Route("api/messages")]
public class MessagesController : Controller
{
    [Authorize("read:messages")]
    [HttpGet]
    public IActionResult GetAll()
    {
        // Return the list of messages
    }

    [Authorize("create:messages")]
    [HttpPost]
    public IActionResult Create([FromBody] Message message)
    {
        // Create a new message
    }
}

Further Reading

Next Tutorial
2. Using your API
Use Auth0 for FREECreate free Account