asp.net – 从Web API的承载令牌返回用户角色

前端之家收集整理的这篇文章主要介绍了asp.net – 从Web API的承载令牌返回用户角色前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在开发一个Web API 2项目。对于认证我正在使用承载令牌。成功认证后,API返回一个JSON对象。
  1. {"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响应中获取用户角色,需要做哪些更改?

解决方法

搜索很多,我发现我可以创建一些自定义属性,并可以设置它们与身份验证票证。以这种方式,您可以自定义响应,以便它可以拥有呼叫者端可能需要的自定义值。

以下是发送用户角色以及令牌的代码。这是我的要求。可以修改代码发送所需的数据。

  1. public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
  2. {
  3. using (UserManager<ApplicationUser> userManager = _userManagerFactory())
  4. {
  5. ApplicationUser user = await userManager.FindAsync(context.UserName,context.Password);
  6.  
  7. if (user == null)
  8. {
  9. context.SetError("invalid_grant","The user name or password is incorrect.");
  10. return;
  11. }
  12.  
  13. ClaimsIdentity oAuthIdentity = await userManager.CreateIdentityAsync(user,context.Options.AuthenticationType);
  14.  
  15. ClaimsIdentity cookiesIdentity = await userManager.CreateIdentityAsync(user,CookieAuthenticationDefaults.AuthenticationType);
  16. List<Claim> roles = oAuthIdentity.Claims.Where(c => c.Type == ClaimTypes.Role).ToList();
  17. AuthenticationProperties properties = CreateProperties(user.UserName,Newtonsoft.Json.JsonConvert.SerializeObject(roles.Select(x=>x.Value)));
  18.  
  19. AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity,properties);
  20. context.Validated(ticket);
  21. context.Request.Context.Authentication.SignIn(cookiesIdentity);
  22. }
  23. }
  24.  
  25.  
  26. public static AuthenticationProperties CreateProperties(string userName,string Roles)
  27. {
  28. IDictionary<string,string> data = new Dictionary<string,string>
  29. {
  30. { "userName",userName },{"roles",Roles}
  31. };
  32. return new AuthenticationProperties(data);
  33. }

这会让我回来了

  1. `{"access_token":"Vn2kwVz...",21 Jun 2014 10:43:05 GMT"
  2. "roles"=["Role1","Role2"] }`

希望这个信息对一些有帮助。

猜你在找的asp.Net相关文章