SteinTech
SteinTech

Reputation: 4068

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

Upvotes: 1

Views: 551

Answers (2)

SteinTech
SteinTech

Reputation: 4068

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

Upvotes: 0

Kirk Larkin
Kirk Larkin

Reputation: 93173

Combine ViewContextAttribute, HttpContext.User and 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:

  1. Using a property decorated with [ViewContext], we can access the ViewContext and its HttpContext property.
  2. Given a 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.
  3. We pass this identityUser value into UserManager.IsInRoleAsync.

Upvotes: 4

Related Questions