ASP.NET Core Web API Authentication

Sample Project

Download this sample project configured with your Auth0 API Keys.

System Requirements
  • .NET Core 1.0
  • Visual Studio 2015 Update 3 (Optional)
  • Visual Studio Code (Optional)
Show requirements

1. Configure the JWT Middleware

Add the JWT middleware to your application's middleware pipeline in order to enable authentication with a JSON Web Token.

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:

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();
}

Signature Validation

Before we carry on, a quick word about the verification of the JWT, as the configuration above may af first glance seem very simplistic.

The JWT middleware will automatically use the Authority to verify the issuer of the JWT, and the Audience to verify the audience. These values need match the values in the token exactly, so ensure you specify the trailing backslash (/) for the Authority as this is a fairly common reason for tokens not verifying correctly.

Next, it will seem as though the JWT middleware configuration above is insecure since the signature is not explicitly verified anywhere. This is however not true, as the JWT middleware will interrogate the /.well-known/openid-configuration endpoint at the URL specified in the Authority property to discover the JSON Web Key Set (JWKS) document. It will then download the JSON Web Key which is subsequently used to verify the token.

This can be confirmed by looking at the Fiddler trace in the screenshot below. Notice that the first time a call is made to the API, that the JWT middleware downloads the JWKS document:

Fiddler trace of retrieval of JWK

If someone tries to create a JWT with another key, the signature verification will fail:

Console output with incorrectly signed JWT

2. Securing an API endpoint

The JWT middleware integrates with the standard ASP.NET Core Authentication and Authorization mechanisms.

You only need to decorate your controller action with the [Authorize] attribute to secure an endpoint:

[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.";
    }
}

3. Using your API

In order to make calls to your API, you will need to obtain an access_token. An access_token can be obtained in a number of ways, depending on the type of application your are building. These are referred to as authorization grant flows, and you can refer to the API Authorization section for more information of the types of flows and to determine which one is most appropriate for your client application.

Once you have obtained an access_token you can pass that along in the Authorization header of requests to your API as a Bearer token.

Here is a sample RAW request:

GET /api/ping/secure HTTP/1.1
Host: localhost:5000
Authorization: Bearer <your access_token>

Or using RestSharp:

var client = new RestClient("http://localhost:5000/api/ping/secure");
var request = new RestRequest(Method.GET);
request.AddHeader("authorization", "Bearer <your access_token>");
IRestResponse response = client.Execute(request);

4. Testing your API in Postman

During development you may want to test your API with Postman. If you make a request to the /ping/secure endpoint you will notice that the API returns an HTTP status code 401 (Unauthorized):

Unauthorized request in Postman

As mentioned in the previous step, you will need to pass along an access_token in the HTTP Authorization header. A quick and easy way to obtain an access_token for test purposes is from the Test tab of your API settings:

Obtain a JWT

You can then use the access_token and pass it along in the Authorization header as a Bearer token:

Authorized request in Postman

Next Step

To learn how to allow only clients who were granted a certain scope access to a particular API endpoint, please continue with the Authorization tutorial.

Previous Tutorial
1. Introduction
Use Auth0 for FREECreate free Account