-
Notifications
You must be signed in to change notification settings - Fork 10.5k
Description
Summary
Make BearerTokenHandler public (instead of internal sealed) to allow customization by overriding its behavior, particularly HandleSignInAsync.
The alternative is creating my own handler which inherits from SignInAuthenticationHandler and implement token authorization myself. This has the possible benefit of allowing custom BearerTokenOptions but is otherwise mostly identical to the existing BearerTokenHandler.
Motivation and goals
I am trying to use AspNetCore.Authentication in combination with ASP.NET Core Identity taking advantage of user and role management. However, in order to comply with company wide API specifications I want to customize the sign in token response.
My goal is to use given access and refresh tokens with all the claims that Asp automatically includes but customize the response body of my sign in endpoint. In other word serving the pregenerated tokens in a different package.
In scope
- Add custom fields to response body on HandleSignInAsync
- Services.AddBearerToken() using custom Handler
Out of scope
- Custom BearerTokenOptions
- Updating AspNetCore.Idenity.AddIdentityApiEndpoints
Risks / unknowns
- Other devs might overcomplicate things by overriting the BearerTokenHandler instead of using existing configuration capabilities
- Overwriting a crucial security class might encompass security risks by introduced by the developer. However, the other classes in Authentication are public as well.
- Other authentication handlers in ASP.NET Core (like JwtBearerHandler, CookieAuthenticationHandler, etc.) are public and overridable. This consistency would support advanced customization scenarios while maintaining the intended structure of the authentication system.
Examples
// ApplicationBearerTokenHandler.cs
public class ApplicationBearerTokenHandler(
IOptionsMonitor<BearerTokenOptions> optionsMonitor,
ILoggerFactory loggerFactory, UrlEncoder urlEncoder
) : BearerTokenHandler (optionsMonitor, loggerFactory, urlEncoder)
{
...
}
// Program.cs
builder.Services.AddAuthentication(IdentityConstants.BearerScheme)
.AddBearerToken<ApplicationBearerTokenHandler>(IdentityConstants.BearerScheme);