.NETCore2如何填充用户而不设置控制器中的Authorize属性 [英] .NETCore2 how to populate User without setting Authorize attribute in controller

查看:398
本文介绍了.NETCore2如何填充用户而不设置控制器中的Authorize属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具有使用中介器模式的请求管道,其中步骤之一是授权.定义一个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)方法?

推荐答案

以下示例代码

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属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆