gpt4 book ai didi

asp.net - 从 Web API 的不记名 token 返回用户角色

转载 作者:行者123 更新时间:2023-12-03 01:12:34 25 4
gpt4 key购买 nike

我正在开发一个 Web API 2 项目。对于身份验证,我使用不记名 token 。身份验证成功后,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 响应中获取用户角色,我需要进行哪些更改?

最佳答案

经过大量搜索后,我发现我可以创建一些自定义属性,并可以使用身份验证票证来设置它们。通过这种方式,您可以自定义响应,以便它可以具有调用方可能需要的自定义值。

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

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"] }`

希望这些信息对某些人有所帮助。 :)

关于asp.net - 从 Web API 的不记名 token 返回用户角色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24096634/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com