Securing an API with JSON Web Tokens (Configuring the API)

To add JWT bearer authentication to an ASP.net Core site, you’ll need to add the JWTBearer middleware to the application. The middleware is found in the Microsoft.AspNetCore.Authentication.JwtBearer namespace, and will allow the service to validate a token, and create a ClaimsPrincipal with the claims in the token. To add the middleware to the service, we’ll start by adding authentication with the options DefaultAuthenticationScheme and DefaultChallengeScheme set to JwtBearerDefaults.AuthenticationScheme. So when the [Authorize] attribute is put on controllers or actions, they will default to use JwtBearer authentication. In the Startup.cs file, there should be a ConfigureServices function that provides you with a IServiceCollection interface to do the configuring.

public void ConfigureServices(IServiceCollection services)
{
     services.AddDbContext<RESTContext>();
     services.AddIdentity<IdentityUser, IdentityRole>()
          .AddEntityFrameworkStores<RESTContext>();

     services.AddAuthentication(options =>
     {
          options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
          options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
     })

...

}

JwtBearer Options

The next service we need to add is the JwtBearer service, which allows configuration with the JwtBearerOptions parameter. Here are a list of several of the options.

  • RequiredHttpsMetadata – JWT bearer tokens should never be passed around without using HTTPS. If someone were to intercept a token, they could use it to impersonate the owner of the token. Always set this option to true.
  • AutomaticAuthenticate – When set to true, it will cause the service to automatically authenticate the user defined in the token.
  • Audience – This value represents the service or resource that will receive the incoming token. Remember that list of registered claims that you can put in the payload of a token? Audience is one of them, and if the value in the token doesn’t match what is placed in this option, the token will be rejected.
  • Authority – The authority option is used to specify the address of the authentication server that issued the token. If you set this option, the middleware will use it to get the public key that is used to validate the token’s signature. It will also verify that the issuer claim found in the token matches this value.
     services.AddAuthentication(options =>
     {
          options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
          options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

     }).AddJwtBearer(options =>
     {
          options.Audience = Configuration["Tokens:Issuer"];
          options.RequireHttpsMetadata = true;  
          
       

Take note that I did not set the Authority option. The code sample is running a web application that issues and authenticates tokens that it creates. It is not reaching out to an authentication server to validate the token’s signature. If you were going to use a third party service to provide authentication, than this option becomes important.

Validation Options

We will also need to set the parameters that are used to validate a token. In ASP.net Core 2, this is done with the TokenValidationParameters object.
These are a list of the relevant options.

  • ValidateIssuer(s) – Do you want to validate the issuer of the token? Generally this gets set to true.
  • ValidIssuer – If you’re going to validate the issuer of the token, this is the value should match the issuer claim in the token.
  • ValidateIssuerSigningKey – Do you want to validate the Issuer’s signing key?
  • IssuerSigningKey – This is the public key used to validate JWT tokens. When you put the key here, it means that the service won’t need access to the token issuing authentication server. It could come from a file, certificate store, or as in the example below a configuration file. BTW don’t use the example below, it’s not your best security option.
     services.AddAuthentication(options =>
     {
          options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
          options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

     }).AddJwtBearer(options =>
     {
          options.Audience = Configuration["Tokens:Issuer"];
          options.RequireHttpsMetadata = true;  
          options.TokenValidationParameters = new TokenValidationParameters
          {
               ValidateIssuerSigningKey = true,
               ValidateIssuer = true,
               ValidIssuer = Configuration["Tokens:Issuer"],
               IssuerSigningKey = new SymetricSecurityKey(Encoding.UTF9.GetBytes(Configuration["Tokens:Key"])),
               ValidateLifetime = true
           };

Now the last thing we need to do here is handle the event that gets fired when authentication has failed.

               ValidateIssuer = true,
               ValidIssuer = Configuration["Tokens:Issuer"],
               IssuerSigningKey = new SymetricSecurityKey(Encoding.UTF9.GetBytes(Configuration["Tokens:Key"])),
               ValidateLifetime = true
           };
          options.Events = new JwtBearerEvents()
          {
               OnAuthenticationFailed = c =>
               {
                    c.NoResult();
                    c.Response.StatusCode = 500;
                    c.Response.ContentType = "text/plain";
                    return c.Response.WriteAsync("An error occurred processing your authentication.");
               }
          };

Applying the Attributes

Once the middleware is configured and added to the pipeline, you can use standard authorize attributes on your controllers.
You could also specify that a controller or action use JwtBearer authentication as part of the attribute if you need to be specific.

[Authorize(AuthenticationSchemess = JwtBearerDefaults.AuthenticationScheme)]

Leave a Reply

Your email address will not be published. Required fields are marked *