How to add roles to the asp identity bearer token

2019-05-31 00:47发布

问题:

I implemented OWIN bearer token authorization, and based on this article: http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/, and now i want to add roles to the bearer token so that i can be able retrieve it on the controller like am doing with the userName...identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName)); and was able to get the username of the current user with User.Identity.Name

回答1:

Check my latest post on bitoftechwhere I read Roles once I generate token, or you can assign roles manually using the ClaimsType.Role like you assign the UserName. Hope this answers your question.



回答2:

http://forums.asp.net/t/1998896.aspx?Cannot+assign+claims+identity+to+a+variable+using+asp+net+WebAPI+with+Oauth+

http://nareshjois.com/custom-information-in-asp-net-identity-cookie-ticket/

i managed to add and read new roles manually by creating a new column in the asp identity AspNetUsers table named RoleName and i added roles directly...

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {

            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            using (AuthRepo _repo = new AuthRepo())
            {
                UserProfile user = await _repo.FindUser(context.UserName, context.Password);

                if (user == null)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }

                /*var claims = new List<Claim>
                {
                    new Claim(ClaimTypes.GivenName, user.FirstName),
                };*/

                var identity = new ClaimsIdentity(context.Options.AuthenticationType);
                identity.AddClaim(new Claim("sub", context.UserName));
                identity.AddClaim(new Claim("role", "user"));
                identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
                identity.AddClaim(new Claim("RoleName", user.RoleName));

                context.Validated(identity);
            }
        }

i then could read a role associated with each user like so

var cp = User as ClaimsPrincipal;   //var cp = (ClaimsPrincipal)User;
var roleName = ((Claim)cp.Claims.SingleOrDefault(x => x.Type == "RoleName")).Value.ToString();

I PERSONALLY FIND THIS EASIER TO MAINTAIN...



回答3:

You can add a function to do so.

 public static AuthenticationProperties CreateProperties(string userName, string Roles)
{
    IDictionary<string, string> data = new Dictionary<string, string>
    {
        { "userName", userName },
        {"roles",Roles}
    };
    return new AuthenticationProperties(data);
}