回答

2

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

+0

感谢Taiseer,我想手动添加的角色当用户注册一个新帐号...会出现在用户选择角色... – kabue7 2015-02-06 15:15:08

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/

我设法通过在ASP身份创建一个新的列直接加入AspNetUsers命名ROLENAME和我表角色手动添加和读取新的角色......

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

我个人认为,这一易于维护...

+0

雅的复选框。它为我工作。 :) – 2016-07-20 05:31:16

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); 
} 
+0

这增加了令牌响应负载,而不是令牌本身。因此,角色/索赔可能会被客户篡改。 – 2016-05-26 22:25:07