gpt4 book ai didi

c# - 如何过期/更新存储在 Web API SessionToken 中的 ClaimsIdentity 声明

转载 作者:太空狗 更新时间:2023-10-29 23:24:09 24 4
gpt4 key购买 nike

我正在使用出色的 Thinktecture.IdentityModel 库在 ASP.NET Web API 项目中执行身份验证/授权,该项目将从移动设备和可能的 Web 客户端使用。我正在使用基本身份验证对移动客户端进行身份验证以访问 Web API,并利用 Thinktecture.IdentityModel 提供的内置 SessionToken 生成。但是,我对如何撤销添加到 ClaimsIdentity 声明集合的声明有一些担忧,然后(我认为)将这些声明编码到提供给客户端的 SessionToken 中......

这是我目前所拥有的:

按照 IdentityModel 示例项目中的示例,我创建了以下类

public static class  SecurityConfig
{
public static void ConfigureGlobal(HttpConfiguration globalConfig)
{
globalConfig.MessageHandlers.Add(new AuthenticationHandler(CreateConfiguration()));
}

public static AuthenticationConfiguration CreateConfiguration()
{
var authentication = new AuthenticationConfiguration()
{
ClaimsAuthenticationManager = new MyClaimsTransformer(),
RequireSsl = false, //TODO:TESTING only
EnableSessionToken = true,
SessionToken = new SessionTokenConfiguration()
{
EndpointAddress = "/Authenticate"
}
};
authentication.AddBasicAuthentication(Membership.ValidateUser);

return authentication;
}
}

像这样从我的 Global.asax 类中调用

SecurityConfig.ConfigureGlobal(GlobalConfiguration.Configuration);

移动设备从个人那里收集用户名和密码,正确设置身份验证 header 并将凭据提供给必要的 Web 端点 http://myhost/api/Authenticate

在服务器上,使用用户名/密码调用我的 Membership.ValidatUser,如果验证通过,则调用 MyClaimsTransformer 的 Authenticate 方法。

public class ClaimsTransformer : ClaimsAuthenticationManager
{
public override ClaimsPrincipal Authenticate(string resourceName, ClaimsPrincipal incomingPrincipal)
{
if (!incomingPrincipal.Identity.IsAuthenticated)
{
return base.Authenticate(resourceName, incomingPrincipal);
}
return incomingPrincipal;
}
}

然后,移动客户端会收到一个 token ,它可以在任何后续请求的身份验证 header 中传递该 token 。

这一切都很好。

现在我想做的是在 ClaimsTransformer 中添加一些代码来执行类似于以下伪代码的操作。

var nameClaim = incomingPrincipal.Claims.First(c => c.Type == ClaimTypes.Name);

//Using value in nameClaim lookup roles or permissions for this user.
var someListofRoles = SomeMethodToGetRoles(nameClaim.Value);

//Add user roles to the Claims collection of the ClaimsPrincipal.
foreach(var role in someListOfRoles)
{
incomingPrincipal.Identities.First().AddClaim(new Claim("Role", role.Name));
}

我希望限制我需要从数据库中请求给定用户的角色或权限列表的次数,并方便在自定义 AuthorizeAttribute 中检查这些角色/权限。

然而,当我开始添加这个时,我开始考虑用户已经登录并收到此 token 的场景,但通过系统的不同用户的某些操作,他们的角色可能会更改或撤销.初始用户仍将拥有此 token ,其中包含现已过期的角色/权限列表,并且在 token 过期之前可以访问任何内容,或者将获得对某些内容的新访问权限但实际上不会获得该访问权限,直到他们以某种方式注销。

是否有一种机制可以使以这种方式创建的 SessionToken 失效?或者,如果我找到某种方式知道已对用户角色/权限进行了更改,我将如何修改声明并以无缝方式重新发出 SessionToken?

此外,如何完全撤销 SessionToken,即如果我想“注销”用户,那将如何工作?

最佳答案

session token 工具没有该功能。我们希望让解决“每次应用程序启动时输入密码”问题变得简单。如果没有完整的数据存储后端(可以在网络农场等中使用),很难实现撤销。

您不应在 session token 中存储可能随 session 时间而改变的数据。

关于c# - 如何过期/更新存储在 Web API SessionToken 中的 ClaimsIdentity 声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15778259/

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