1

我实现了OWIN不记名令牌授权,并基于这篇文章:http ://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity /,现在我想将角色添加到不记名令牌中,这样我就可以像使用用户名一样在控制器上检索它......identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));并且能够获取当前用户的用户名User.Identity.Name

4

3 回答 3

1

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

于 2015-02-06T15:07:18.220 回答
1

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

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

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

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

我个人觉得这更容易维护......

于 2015-02-07T11:46:43.333 回答
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);
}
于 2016-01-13T14:04:45.383 回答