Reputation: 4822
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?
Upvotes: 2
Views: 652
Reputation: 13704
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.
Upvotes: 0
Reputation: 4822
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.
Upvotes: 1