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




