Search code examples
authorizationasp.net-identityidentityserver4

Authorizing a user based on claims when using a reference token


I am using a reference token to get the users claims as the JWT token was too long. This works fine from a client controller:

var introspectionClient = new IntrospectionClient(
    "http://localhost:5000/connect/introspect",
    "api1",
    "secret");

var response = await introspectionClient.SendAsync(
    new IntrospectionRequest { Token = await HttpContext.GetTokenAsync("access_token") });

ViewBag.Json = Json(response.Json).Value;
return View("json");

As I can use HttpContext to retrieve the access token and exchange it for the users claims at the introspection endpoint.

However from the authorization handler I cannot access the HttpContext to get the access token and the AuthorizationHandlerContextonly contains claims from the id token.

I'm open to all suggestions but it does feel like there should be a way to get the access token in the authorization handler but i could well be wrong.

Thanks in advance for your time.


Solution

  • I do not know if this is the way you should do it. But to answer your question, you can inject the context like this:

    //using Microsoft.AspNetCore.Authentication;
    
    public class MyAuthorizationHandler : AuthorizationHandler<MyRequirement>
    {
        private IHttpContextAccessor _httpContextAccessor;
    
        public MyAuthorizationHandler(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }
    
        protected async override Task HandleRequirementAsync(AuthorizationHandlerContext context, MyRequirement requirement)
        {
            var token = await _httpContextAccessor.HttpContext.GetTokenAsync("access_token");
        }
    }
    

    You will need to make HandleRequirementAsync async. You don't have to add IHttpContextAccessor in startup to the services. This is already done by Identity.