[英]how to access authorized user a custom tag helper
I'm trying to verify if the current authorized is in a specific role, using a custom tag helper. 我正在尝试使用自定义标签帮助程序来验证当前授权的用户是否具有特定角色。 I want to use
UserManager.IsInRoleAsync()
, but I need to pass in a User
object. 我想使用
UserManager.IsInRoleAsync()
,但是我需要传递一个User
对象。
How can I access the current authorized user? 如何访问当前的授权用户?
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
base.PreProcess(context, output);
bool isInRole = _um.IsInRoleAsync(????, this.Roles); ;
var policy = await AuthorizationPolicy.CombineAsync(_policy, new[] { this });
var authResult = await _eva.AuthenticateAsync(policy, _http.HttpContext);
var authorizeResult = await _eva.AuthorizeAsync(policy, authResult, _http.HttpContext, null);
}
Combine ViewContextAttribute
, HttpContext.User
and UserManager.GetUserAsync
: 结合使用
ViewContextAttribute
, HttpContext.User
和UserManager.GetUserAsync
:
[ViewContext]
public ViewContext ViewContext { get; set; }
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
// ...
var claimsPrincipal = ViewContext.HttpContext.User;
var identityUser = await _um.GetUserAsync(claimsPrincipal);
if (identityUser == null)
{
// Either no user is signed in or there's no match for the user in Identity.
// ...
}
bool isInRole = _um.IsInRoleAsync(identityUser, this.Roles);
// ...
}
Here's a breakdown of what's happening: 这是正在发生的事情的分解:
[ViewContext]
, we can access the ViewContext
and its HttpContext
property. [ViewContext]
的属性,我们可以访问ViewContext
及其HttpContext
属性。 HttpContext
, we can access its User
property and pass that into a call to UserManager.GetUserAsync
, which returns the IdentityUser
(or custom type) used by the Identity implementation. HttpContext
,我们可以访问其User
属性,并将其传递给对UserManager.GetUserAsync
的调用,该调用返回Identity实现使用的IdentityUser
(或自定义类型)。 identityUser
value into UserManager.IsInRoleAsync
. identityUser
值传递给UserManager.IsInRoleAsync
。 I ended up rewriting some of the logic:: 我最终重写了一些逻辑:
var foo = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser();
if (!this.Roles.IsNull())
{
foo.RequireRole(this.Roles.Split(","));
}
if (!this.AuthenticationSchemes.IsNull())
{
foo.AddAuthenticationSchemes(this.AuthenticationSchemes);
}
var policy = foo.Build();
var authResult = await _eva.AuthenticateAsync(policy, _http.HttpContext);
var authorizeResult = await _eva.AuthorizeAsync(policy, authResult, _http.HttpContext, null);
if (!authorizeResult.Succeeded)
{
output.SuppressOutput();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.