asp.net – 从Web API的承载令牌返回用户角色
发布时间:2020-12-16 00:36:38 所属栏目:asp.Net 来源:网络整理
导读:我正在开发一个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":"S
我正在开发一个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...",21 Jun 2014 10:43:05 GMT" "roles"=["Role1","Role2"] }` 希望这个信息对一些有帮助。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net-mvc – MVC包含路径无效错误
- 从ASP.NET Core Web API将多GB文件流式传输到AWS S3
- asp.net-mvc – ASP.Net MVC中的多项目领域3
- ASP.Net Core 2.0 Webapi设置了log4net
- asp.net-mvc – 大型Web应用程序中的Windows Workflow用法
- ASP页面的ASP.NET cookie
- .net core 3.0web_razor page项目_使用中间件接受大文件上传
- 如何在ASP.NET MVC中记录未处理的异常?
- asp.net-mvc – Web项目需要使用Razor语法3.0.0.0缺少Web组
- 初识ABP vNext(12):模块的独立运行与托管