.NETCore2 how to populate User without setting Authorize attribute in controller

Have request pipeline using mediator pattern where one of the steps is Authorization. Have an AdminAuthorizer class defined like:

public AdminAuthorizer(IHttpContextAccessor httpContextAccessor)
    _httpContextAccessor = httpContextAccessor;

public virtual async Task Authorize(TRequest message)
    var user = _httpContextAccessor.HttpContext.User;

Problem is that if I don't specify the [Authorize] in the controller action the HttpContext.User is 'empty'. If apply [Authorize] User is populated with info in my JWT token.

public async Task<IActionResult> SetActive(SetActiveCommand activeMessage)
    await _mediator.Send(activeMessage);
    return Ok();

What do I need to do to be able to obtain the HttpContext.User in the requests were using my Authorize(TRequest message) method?

enter image description here

1 answer

  • answered 2017-10-11 10:08 Riga

    Following code example here ASP.NET Core Authorization Lab:Step 2: Authorize all the things could request authorization for all requests with a filter.

    services.AddMvc(config =>
        var policy = new AuthorizationPolicyBuilder()
        config.Filters.Add(new AuthorizeFilter(policy));

    This is neither what I want but realized that if want the user without having to specify the [Authorize] attribute should get the token from the Request.Headers and decode it myself.