【问题标题】:how to access authorized user a custom tag helper如何访问授权用户自定义标签助手
【发布时间】:2019-06-30 21:44:25
【问题描述】:

我正在尝试使用自定义标签助手验证当前授权是否处于特定角色。我想使用UserManager.IsInRoleAsync(),但是我需要传入一个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);
}

【问题讨论】:

    标签: c# authentication asp.net-core asp.net-core-identity


    【解决方案1】:

    结合ViewContextAttributeHttpContext.UserUserManager.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);
    
        // ...
    }
    

    以下是正在发生的事情的细分:

    1. 使用用[ViewContext] 装饰的属性,我们可以访问ViewContext 及其HttpContext 属性。
    2. 给定一个HttpContext,我们可以访问它的User 属性并将其传递给UserManager.GetUserAsync 的调用,该调用返回Identity 实现使用的IdentityUser(或自定义类型)。
    3. 我们将此identityUser 值传递给UserManager.IsInRoleAsync

    【讨论】:

      【解决方案2】:

      我最终重写了一些逻辑::

      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();
          }
      

      【讨论】:

        猜你喜欢
        • 2019-11-07
        • 2017-04-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-05-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多