.NETCore2 how to populate User without setting Aut

2019-08-03 23:26发布

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.

[Authorize]
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

2条回答
唯我独甜
2楼-- · 2019-08-03 23:59

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()
                     .RequireAuthenticatedUser()
                     .Build();
    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.

查看更多
唯我独甜
3楼-- · 2019-08-04 00:10

You can instruct ASP.NET Core to do the authentication bit without resorting to authorization. This is done by specifying a default authentication scheme in the authentication configuration:

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication("<your-authentication-scheme>");
    }

    public void Configure(IApplicationBuilder app)
    {
        app.UseAuthentication();
    }
}

Doing so means ASP.NET Core will execute the authentication handler associated with the scheme you specified for every request.

查看更多
登录 后发表回答