gpt4 book ai didi

c# - 缩短 OWIN 在 ASP.NET WebAPI 2 中返回的访问 token

转载 作者:太空宇宙 更新时间:2023-11-03 12:55:29 25 4
gpt4 key购买 nike

我们使用 ASP.NET WebAPI 2 开发了 REST API,并使用 ASP.NET Identity 对其进行保护。客户要求将他们的 token 设置为较长的​​到期时间,因为他们将访问 token 存储在他们的数据库中。

在测试期间,他们要求我们减少 token 的长度,因为他们的数据库最多只能处理 250 个字符的字符串。我们的实现非常“ Vanilla ”。以下是我们当前为不记名 token 设置的选项:

OAuthOptions = new OAuthAuthorizationServerOptions {
TokenEndpointPath = new PathString("/oauth/2/token"),
Provider = new ApplicationOAuth2Provider(PublicClientId),
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1000000),
AllowInsecureHttp = true
};

我们如何将 token 缩短到 250 个字符的限制?我注意到一些与设置自定义访问 token 格式化程序等相关的属性,但我不确定如何实现这些以及有哪些限制和/或陷阱。

如有任何帮助,我们将不胜感激。

最佳答案

答案是肯定的。

由于客户端只是将相同的 token 字符串发送回服务器,您可以发送 token 的哈希值。

我所做的是使用 GUID 来表示 token ,它只有 32 个字符。并将映射信息(GUID => token)存储在服务器端。当用户尝试通过 GUID 进行身份验证时,您可以从存储它的位置读取 REAL token ,然后反序列化票证。

这里是示例代码,核心是重写OAuthAuthorizationServerOptions类的OnCreate/OnReceive方法。您可能还想覆盖 OnCreateAsyncOnReceiveAsync

OAuthOptions = new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/Token"),
Provider = new ApplicationOAuthProvider(PublicClientId),
AccessTokenProvider = new AuthenticationTokenProvider
{
OnCreate = (context) =>
{
var token = context.SerializeTicket();
var guid = Guid.NewGuid().ToString("N");
// You need to implement your own logical here, for example, store the mapping (guid => token) into database
RedisServer.SetValue(guid, token, TimeSpan.FromDays(Consts.AccessTokenExpireDays));
context.SetToken(guid);
},
OnReceive = (context) =>
{
var token = RedisServer.GetValue(context.Token);
context.DeserializeTicket(token);
}
},
AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(Consts.AccessTokenExpireDays),
// In production mode set AllowInsecureHttp = false
AllowInsecureHttp = true,
};

关于c# - 缩短 OWIN 在 ASP.NET WebAPI 2 中返回的访问 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34067421/

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