Asp.net

從 Web API 的不記名令牌返回使用者角色

  • June 7, 2014

我正在開發一個 Web API 2 項目。對於身份驗證,我使用不記名令牌。成功認證後,API 返回一個 JSON 對象。

{"access_token":"Vn2kwVz...",
  "token_type":"bearer",
  "expires_in":1209599,
  "userName":"username",
  ".issued":"Sat, 07 Jun 2014 10:43:05 GMT",
  ".expires":"Sat, 21 Jun 2014 10:43:05 GMT"}

現在我想在這個 JSON 對像中返回使用者角色。為了從 JSON 響應中獲取使用者角色,我需要進行哪些更改?

經過大量搜尋後,我發現我可以創建一些自定義屬性並可以使用身份驗證票進行設置。通過這種方式,您可以自定義響應,以便它可以具有呼叫方可能需要的自定義值。

這是將使用者角色與令牌一起發送的程式碼。這是我的要求。可以修改程式碼以發送所需的數據。

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
   {
       using (UserManager<ApplicationUser> userManager = _userManagerFactory())
       {
           ApplicationUser user = await userManager.FindAsync(context.UserName, context.Password);

           if (user == null)
           {
               context.SetError("invalid_grant", "The user name or password is incorrect.");
               return;
           }

           ClaimsIdentity oAuthIdentity = await userManager.CreateIdentityAsync(user,
               context.Options.AuthenticationType);

           ClaimsIdentity cookiesIdentity = await userManager.CreateIdentityAsync(user,
               CookieAuthenticationDefaults.AuthenticationType);
           List<Claim> roles = oAuthIdentity.Claims.Where(c => c.Type == ClaimTypes.Role).ToList();
           AuthenticationProperties properties = CreateProperties(user.UserName, Newtonsoft.Json.JsonConvert.SerializeObject(roles.Select(x=>x.Value)));

           AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
           context.Validated(ticket);
           context.Request.Context.Authentication.SignIn(cookiesIdentity);
       }
   }


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

這將使我返回輸出為

`{"access_token":"Vn2kwVz...",
"token_type":"bearer",
"expires_in":1209599,
"userName":"username",
".issued":"Sat, 07 Jun 2014 10:43:05 GMT",
".expires":"Sat, 21 Jun 2014 10:43:05 GMT"
"roles"=["Role1","Role2"] }`

希望這些資訊對某人有所幫助。:)

引用自:https://stackoverflow.com/questions/24096634