Skip to content

When using Custom Authentication handler, httpContext.User is not getting updated even after token validation is successful #48053

@askids

Description

@askids

hi,

I am using .Net 6 WebApi. I have a need to support dual authentication scheme. One scheme is using standard OIDC provided Access token for which I am using the standard AddJwtBearer extension method with tokenvalidation parameters. For second scheme, I have created a custom Authentication Handler using the .Net's own JwtBearerHandler.cs code as reference.

https://github.com/dotnet/aspnetcore/blob/a450cb69b5e4549f5515cdb057a68771f56cefd7/src/Security/Authentication/JwtBearer/src/JwtBearerHandler.cs

For initial implementation, except for changing from Bearer to CustomBearer and changing the class name, I haven't done any other changes, so that easier to troubleshoot during initial development.

I also have some custom AuthorizationHandler classes for applying custom Authorization policies.

The problem that I am facing is that even though the authentication of the incoming JWT is happening successfully in the Custom Authentication Handler and I am setting the TokenValidateContext with the claim principle from the incoming JWT, I am not seeing httpContext.User updated with the proper identity from token, when I access httpContext in other places within the app.

Even in the Custom Authorization Handler's HandleRequirementAsync method, the AuthorizationHandlerContext does not have the authenticated user identity information. So my subsequent authorization handler fails the request as no user information is available from the Claims Principle.

I am facing this issue, only when Authentication goes through my custom authentication handler class. If I am passing the standard OIDC provided access_token, httpContext.User and AuthorizationHandlerContext, both reflect the authenticated user principle as available from token.

So i am thinking that I am missing some step in between after completing the authentication which is causing the httpContext.User not to reflect the authenticated User Principle information.

In my custom authentication handler's HandleAuthenticateAsync method, after successful validation of the token, should I simply overwrite httpContext.User with the Principle created from the token? Or is there any other standard way to update the value as the reference JwtBearerHandler.cs does not perform any such action.

Any guidance on this will be very helpful.

Thanks!

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-authIncludes: Authn, Authz, OAuth, OIDC, Bearer

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions