Search code examples
c#authenticationasp.net-coreasp.net-core-identity

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.

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

Solution

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