dotnet / dotnet/aspnetcore

Expose BearerTokenHandler from Microsoft.AspNetCore.Authentication

Open
#63,127 1 comment 2 reactions 0 assignees View on GitHub
area-auth design-proposal
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 6h
Merged PRs (30d)
290

Description

## Summary

Make [BearerTokenHandler](https://github.com/dotnet/aspnetcore/blob/fab448a153e8e2683a652f1fd1e8ef7d917c3110/src/Security/Authentication/BearerToken/src/BearerTokenHandler.cs) 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](https://github.com/dotnet/aspnetcore/blob/fab448a153e8e2683a652f1fd1e8ef7d917c3110/src/Security/Authentication/Core/src/SignInAuthenticationHandler.cs#L14) 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 optionsMonitor,
ILoggerFactory loggerFactory, UrlEncoder urlEncoder
) : BearerTokenHandler (optionsMonitor, loggerFactory, urlEncoder)
{
...
}

// Program.cs
builder.Services.AddAuthentication(IdentityConstants.BearerScheme)
.AddBearerToken(IdentityConstants.BearerScheme);

```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.