.NETCore2如何填充用户而不设置控制器中的Authorize属性

编程入门 行业动态 更新时间:2024-10-18 01:42:19
本文介绍了.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)方法?

推荐答案

以下示例代码 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属性

本文发布于:2023-11-17 12:26:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1609996.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:而不   属性   器中   用户   Authorize

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!