liveBook · Manning

Bearer authentication

As explained in .NET in Action, Second Edition

Bearer authentication is an HTTP authentication method in which possession of a bearer token grants access to a protected resource.

Bearer authentication grants access to a protected resource to whoever possesses the token. An API request carries it in the HTTP Authorization header, prefixed with “Bearer.” section 9.6

The token shown is a JWT with a header, payload, and signature. The signature is checked against a signing key to help ensure the token’s contents were not tampered with. section 9.6

Keep authentication and authorization distinct when protecting API operations:

  • A bearer token identifies an authenticated caller; named authorization policies can allow all authenticated users to read catalog data while reserving create, update, and delete operations for one identity. section 9.6
  • Inspect tokens cautiously: they may contain personal information and remain usable until expiration. A local decoder such as DevToys is safer than pasting a token into a browser tool. section 9.6
Listing 9.22 Custom authorization requirement and handler
using Microsoft.AspNetCore.Authorization;
  
namespace ManningBooksApi;
  
public class OnlyMeRequirement :                     #1
  IAuthorizationRequirement { }                      #2
  
public class OnlyMeRequirementHandler :
  AuthorizationHandler<OnlyMeRequirement>            #3
{
  protected override Task HandleRequirementAsync(    #4
    AuthorizationHandlerContext context,             #5
    OnlyMeRequirement requirement)
  {
    if (context.User != null)                        #6
    {
      var emailClaim = context.User
        .FindFirst("preferred_username");            #7
      if (emailClaim != null
        && emailClaim.Value == "your@email.com")     #8
      {
        context.Succeed(requirement);                #9
      }
    }
  
    return Task.CompletedTask;                       #10
  }
}

The custom authorization handler checks the preferred_username claim before satisfying the requirement. section 9.6

How .NET in Action, Second Edition covers it

How deep it goes
Inspects the Authorization header and JWT structure, then configures policy-based access using authenticated users and claims.
Examples
Uses Swagger UI to inspect a JWT and distinguishes authenticated-user reads from mutations reserved for one identity.
What you can do after
Apply bearer authentication through Swagger UI and configure ASP.NET authorization policies for authenticated users and a claim-matched identity.
How it connects
Connects bearer authentication to JWTs, authorization headers, authentication schemes, authorization policies, and claims.

Also explained in

Compare how 5 books explain bearer authentication →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of .NET in Action, Second Edition. The section links point to the parts of the book it draws on.