dotnet / AspNetCore.Docs

Documentation for ASP.NET Core
https://docs.microsoft.com/aspnet/core
Creative Commons Attribution 4.0 International
12.55k stars 25.3k forks source link

How do I create a claim? #9244

Closed IndigoHealth closed 4 years ago

IndigoHealth commented 5 years ago

This documentation does a great job of explaining what a claim is and how to check for a claim. But how do I create a claim? And (for those of us coming from previous versions of ASP.NET) how do Role claims play with User.IsInRole? Apparently, Roles (as represented in the SQL database) are deprecated (see: https://github.com/aspnet/Identity/issues/1813).


Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

Rick-Anderson commented 5 years ago

@blowdart

blowdart commented 5 years ago

var claim = new Claim(...)

OK that's not useful, but really it's a concern of whatever identity system you're using, be it ASP.NET Identity, ADFS, AAD and so on. Role claims appear as, well, role claims, so you can check however you like. But it's not a suitable place to document this, it's authentication, not authorization

IndigoHealth commented 5 years ago

I understand that this page is focused on Authorization based on Claims. But that begs the obvious question of how to create claims in the first place. The section of this page that explains the concept of a claim would be a great place to put a link to a topic that talks about how to create them.

I spent two days trying to get legacy Roles to work. After I stumbled across the discussion that said, in effect, "give up on legacy Roles and use Claims", I went looking for the answer to how to do that. The only topic that I've found that describes claims creation is the "Additional Claims" topic, which talks about OAuth and includes a lot of ugly details that I assume I don't need to figure out for Role-based authorization. And I'm still left with a lot of reading between the lines and experimenting to try to figure out how to create simple Role claims.

lukesdm commented 5 years ago

Any chance of reopening this please? This page is the top result for 'aspnet core identity claims'. For now, this article provides some info on creating claims: https://damienbod.com/2018/10/30/implementing-user-management-with-asp-net-core-identity-and-custom-claims/ The key seems to be the UserClaimsPrincipleFactory classes

damienbod commented 5 years ago

@lukesdm https://github.com/damienbod/AspNetCoreAngularSignalRSecurity/blob/master/StsServerIdentity/Startup.cs#L93-L94

you need to implement the IUserClaimsPrincipalFactory and use an ApplicationUser class which implements the IdentityUser in the Identity context.

This took a while to find, I think this would be good in the Docs.

@Rick-Anderson @blowdart I could add something here if you're interested.

Rick-Anderson commented 5 years ago

@Rick-Anderson @blowdart I could add something here if you're interested.

@damienbod that would be great.

damienbod commented 5 years ago

@Rick-Anderson @blowdart @NTaylorMullen

Something like this: (New Page?)

Adding custom claims to ASP.NET Core Identity

This covers a lot already:

https://docs.microsoft.com/en-us/aspnet/core/security/authentication/add-user-data

So it's just really the last point which is missing from the docs

IndigoHealth commented 5 years ago

There are a couple of foundational concepts that I don't see in your list.

alexanderbikk commented 5 years ago

Here is a very good and simple example of how to add data in Asp.Net Identity claims https://korzh.com/blogs/net-tricks/aspnet-identity-store-user-data-in-claims

Thank for Jon P Smith, I found this link in his repository

jwefers commented 5 years ago

I want to validate the scope claim of an incoming JWT token, where its called "scp". ASP.Net core maps this to the ClaimType "http://schemas.microsoft.com/identity/claims/scope". Can anyone tell me where these strings are defined? System.Security.Claims.ClaimTypes only contains values for "http://schemas.xmlsoap.org/ws/2009/09/identity/claims/..." and its missing scopes. Clearly, there must be another, newer class for this newer schema.

mchudinov commented 4 years ago

How to create claims without using Entity Framework ? How to just add claims to ClaimsPrincipal object during the login process?

enetstudio commented 4 years ago

I'm using the IClaimsTransformation interface, which is deemed a better choice, in my Server Blazor App to add claims to the Claims Principal object.

public class ApplicationUserClaimsTransformation : IClaimsTransformation
{
    private readonly UserManager<ApplicationUser> _userManager;
    public  ApplicationUserClaimsTransformation(UserManager<ApplicationUser> 
                                                                                      userManager)
    {
        _userManager = userManager;
    }

    // Each time HttpContext.AuthenticateAsync() or 
    //   HttpContext.SignInAsync(...) are called, the claims  transformer is 
   // invoked. 
      public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
    {
        var identity = principal.Identities.FirstOrDefault(c => 
                               c.IsAuthenticated);
        if (identity == null) return principal;

        var user = await _userManager.GetUserAsync(principal);
        if (user == null) return principal;

        if (!principal.HasClaim(c => c.Type == ClaimTypes.Country))
        {
            identity.AddClaim(new Claim(ClaimTypes.Country, user.Country));
        }

        if (!principal.HasClaim(c => c.Type == ClaimTypes.DateOfBirth))
        {
            identity.AddClaim(new Claim(ClaimTypes.DateOfBirth, 
                                    user.Birthdate.ToString()));
        }
        return new ClaimsPrincipal(identity);
    }
 }

You need also this in Startup.ConfigureServices method:

  services.AddScoped<IClaimsTransformation, 
                                   ApplicationUserClaimsTransformation>();
reasonet commented 4 years ago

The following link explains how to add claims. I think it should be added to this page: https://docs.microsoft.com/en-us/aspnet/core/security/authentication/cookie?view=aspnetcore-3.1

The relevant code (for me) at the link is: await HttpContext.SignInAsync( CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity), authProperties);

If you added that text to this page, you would answer this question.