[英]What's the pattern for sharing a RestAPI token?
Is there a pattern for how should I store and reuse a restAPI authorisation token across multiple classes?我应该如何在多个类中存储和重用 restAPI 授权令牌?
I'm consuming a RestAPI, my login code takes a user, password and server and then returns an auth token.我正在使用一个 RestAPI,我的登录代码需要一个用户、密码和服务器,然后返回一个身份验证令牌。 That login code sits in a common base class for all my RestAPI calls which works fine.
该登录代码位于我所有的 RestAPI 调用的通用基础 class 中,它工作正常。 But each new object doesn't know the token so has to reauthorise.
但是每个新的 object 都不知道令牌,因此必须重新授权。 I need them to share the same token once it's been generated.
我需要它们在生成后共享相同的令牌。 I can't use a singleton as I may have to login with multiple different users in the same session.
我不能使用 singleton,因为我可能必须在同一个 session 中使用多个不同的用户登录。
I'm sure there's a pattern for that but I can't find it, can you help?我确定有一个模式,但我找不到它,你能帮忙吗?
What you need is a cache.你需要的是一个缓存。 The login service can be a singleton that cache access tokens, you can use a concurrent dictionary to implement the access tokens cache.
登录服务可以是缓存访问令牌的 singleton,您可以使用并发字典来实现访问令牌缓存。
Something like this:像这样的东西:
public class LoginService
{
private ConcurrentDictionary<string, string> accessTokenCache = new ConcurrentDictionary<string, string>();
private string callServerLogin(string user, string password)
{
throw new NotImplementedException();
}
public string Login(string user, string password)
{
var accessToken = callServerLogin(user, password);
accessTokenCache[user] = accessToken;
return accessToken;
}
public bool TryGetCachedAccessToken(string user, out string accessToken )
{
return this.accessTokenCache.TryGetValue(user, out accessToken);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.