asp.net – 从Web API的承载令牌返回用户角色
发布时间:2020-05-29 20:43:46 所属栏目: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
|
我正在开发一个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 – 给定htmlHelper动作名称,如何找出控制器名称
- ide – 我如何处理必须编写经典ASP的代码?
- ASP.NET MVC,Ninject,每个请求多个构造函数的单个实例
- ASP.NET:预编译文件的文件名生成规则
- asp.net – Sitecore – System.Security.Cryptography.Cry
- asp.net-mvc – 部署同一应用程序的2个版本
- asp.net-mvc – 在ASP.NET MVC中使用DotNetOpenId Remember
- asp.net-core – 当前的运行时目标框架与项目不兼容
- 我可以在.NET中设置IIS MIME类型吗?
- asp.net-mvc – 具有错误的剃刀语法编译时不应该编译
推荐文章
站长推荐
- ASP.NET Page_Init被解雇了两次!
- ASP.NET Forms Authentication阻止在Login.aspx上
- asp.net – 如何创建Generic StateManagedCollec
- asp.net-mvc – 实时ASP.NET MVC Web应用程序
- asp.net – SSRS与自定义Web UI
- asp.net-mvc – ASP.NET MVC:对动作执行AJAX请求
- asp.net-mvc – 操作可能会破坏运行时的稳定性:
- 如何在ASP.Net MVC中执行301永久重定向路由
- asp.net-mvc – 为什么我的Html帮助者没有智能感
- 从asp.net mvc生成PDF文件
热点阅读
