New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Consider HasClaimAsync or GetClaimAsync #2068

Open
vankampenp opened this Issue Nov 14, 2018 · 0 comments

Comments

Projects
None yet
2 participants
@vankampenp

vankampenp commented Nov 14, 2018

It is easy to get a claim from a logged in user, but not from a user that is not (yet) logged in.

When generating a JWT token for my API, I want to check if the user for which the credentials are provided has the right claim to allow access to the API. Without such a check the token is provided, but than using the token fails because the access policy checks the claim.

When using Roles you can use IsInRoleAsync(). But there is no equivalent for claims.

So when getting the user:

var user = await _userManager.FindByNameAsync(model.Email);

I would like to do something like:

if (!await _userManager.HasClaimAsync(user, "IsApiUser", "true"))
            {
                               return BadRequest("Invalid user or password");
            }

I have now written my own extension method:

public static async Task<bool> HasClaimAsync(this UserManager<ApplicationUser> userManager,  ApplicationUser user, string claimType, string value)
       {
           var claims = await userManager.GetClaimsAsync(user);
           var claim = claims.FirstOrDefault(c => c.Type == claimType);
           return claim !=null &&  claim.Value == value;
       }

I understand that HasClaim is based on cookies rather than database access, so much cheaper for logged in users:
var valid = User.HasClaim(c => c.Type == "IsApiUser" && c.Value == "true");
But I think the HasClaimAsync or an more generic GetClaimAsync is missing for cases such as the above.

@blowdart blowdart added the Features label Nov 29, 2018

@blowdart blowdart added this to the 3.0.0 milestone Nov 29, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment