回答

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