How to add roles to the asp identity bearer token

2019-05-31 00:37发布

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

3条回答
孤傲高冷的网名
2楼-- · 2019-05-31 01:06

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楼-- · 2019-05-31 01:22

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);
}
查看更多
Summer. ? 凉城
4楼-- · 2019-05-31 01:29

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.

查看更多
登录 后发表回答