问题描述
具有使用中介器模式的请求管道,其中步骤之一是授权.定义一个AdminAuthorizer类,如下所示:
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;
...
}
问题是,如果我未在控制器操作中指定[Authorize],则HttpContext.User为空".如果适用,请使用我的JWT令牌中的信息填充[授权]用户.
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();
}
我需要做些什么才能获得HttpContext.请求中的用户正在使用我的Authorize(TRequest message)方法?
推荐答案
以下示例代码 ASP.NET核心授权实验室:步骤2:授权所有内容可以使用过滤器请求所有请求的授权.
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));
});
这不是我想要的,但意识到如果不需要指定[Authorize]属性的用户,应该从Request.Headers获取令牌并自行对其进行解码.
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.
这篇关于.NETCore2如何填充用户而不设置控制器中的Authorize属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!