首页 文章

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

提问于
浏览
1

我实现了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 回答

  • 1

    您可以添加一个功能来执行此操作 .

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

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

  • 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();
    

    I PERSONALLY FIND THIS EASIER TO MAINTAIN...

相关问题