作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一个 ASP.Net Core 2.1 Web API,使用 OAuth 身份验证。此外,我们使用基于声明的身份验证,声明编码在身份验证 token 中。
这已经运行良好一段时间了,但最近,当出现一个新要求时,事情变得失控,该要求大大增加了必须存储在 token 中的声明数量。长话短说,我们现在的身份验证 token 太长,以至于我们必须重新配置服务器以允许超过 128k 的 header 。
这显然是站不住脚的;仅从网络流量的角度来看,必须发送超过 100k 的 header 以及最简单的 GET 请求是荒谬的。所以现在我的想法如下:不用在 token 中对声明进行编码,只需使用 Guid token 并将声明与 token 一起存储在数据库中,因此当我们验证 token 时我们可以同时提取 claim 并在本地进行交换。
从理论上讲,这应该一下子解决我们的整个问题,但我只是停留在实现细节上,具体来说:由于基于声明的身份验证期望找到身份验证 token 中编码的声明,我该如何交换包含所有声明的 Guid 身份验证 token ?现有代码:
public class MyAuthenticationEvents : OAuthValidationEvents
{
public override async Task ValidateToken(ValidateTokenContext context)
{
if (context.Properties.ExpiresUtc < DateTime.UtcNow)
{
context.Fail("Access Token has expired.");
return;
}
if (!await TokenIsValidAsync(context)) // code to validate the auth token against the database, could be modified to return claims
{
context.Fail("Access Token has not been properly set or has been invalidated.");
return;
}
// Here I would expect to do some skullduggery to switch the compact Guid token for a large token containing claims
context.Success();
}
}
正确的语法是什么?或者我是不是找错了方向,有一个完全更好的方法来实现我的目标?
最佳答案
结果非常简单。我在 ValidateToken() 方法中所需要做的就是使用我根据序列化声明重建的 ClaimsIdentity
创建一个新的 ClaimsPrincipal
我存储在数据库中:
... // create claimsIdentity from serialized claims
context.Principal = new ClaimsPrincipal(claimsIdentity);
context.Success();
}
需要注意一件事:在首次登录时,必须返回 Subject
声明,因此在 HandleTokenRequest()
方法中我们仍然需要:
identity.AddClaim(new Claim(OpenIdConnectConstants.Claims.Subject, user.Username));
关于asp.net-core - 如何在服务器端交换授权 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52622279/
我是一名优秀的程序员,十分优秀!