如何向asp身份承载令牌添加角色

时间:2015-02-06 13:05:40

标签: asp.net asp.net-web-api access-token user-roles bearer-token

我实现了OWIN承载令牌授权,并基于这篇文章:http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/,现在我想将角色添加到持票人令牌,以便我能够在控制器上检索它,就像我在使用userName ... identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));并且能够使用User.Identity.Name

获取当前用户的用户名

3 个答案:

答案 0 :(得分:1)

检查我bitoftech上的最新帖子,在我生成令牌后我读取角色,或者您可以使用ClaimsType.Role手动分配角色,就像分配用户名一样。 希望这能回答你的问题。

答案 1 :(得分:1)

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/

我设法通过在名为 RoleName 的asp身份AspNetUsers表中创建一个新列来手动添加和读取新角色,并且我直接添加了角色......

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);
            }
        }
然后,我可以阅读与每个用户相关的角色,如此

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

我个人觉得维护起来更容易......

答案 2 :(得分:0)

您可以添加一个功能。

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