JWT authentication in ASP.NET Core

Posted: (EET/GMT+2)

 

JSON Web Tokens (JWT for short) are a simple way to pass user identity between a client and an API. Instead of session cookies, the client sends a signed token with each request, and the server validates it.

ASP.NET Core makes this easy with the JWT bearer authentication middleware. You just add a few lines in Startup.cs. Here's an example:

// Startup.cs
public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication("Bearer")
        .AddJwtBearer("Bearer", options =>
        {
            options.Authority = "https://login.example.com";
            options.Audience = "myapi";
        });

    services.AddMvc();
}

Then, enable the authentication in the Configure() method:

// Startup.cs
public void Configure(IApplicationBuilder app)
{
    app.UseAuthentication();
    app.UseMvc();
}

Once configured, any controller or action can require authentication:

[Authorize]
public class ValuesController : Controller
{
    [HttpGet]
    public IActionResult Get()
    {
      return Ok(new[] { "value1", "value2" });
    }
}

The token is validated automatically on each request. You can issue tokens from Azure AD, IdentityServer, or your own STS. JWT works especially well for APIs that serve web and mobile clients.