我已经为我的身份验证实现了自定义 CredentialsAuthProvider
,并将其与内存 session 存储中的默认值一起使用。
现在我尝试将 session 存储更改为 Redis,并将其添加到 AppHost
中的 Configure()
方法中:
container.Register<IRedisClientsManager>(c =>
new PooledRedisClientManager("localhost:6379"));
container.Register<ICacheClient>(c => (ICacheClient)c
.Resolve<IRedisClientsManager>()
.GetCacheClient()).ReusedWithin(Funq.ReuseScope.None);
现在,当我进行身份验证时,我可以看到带有 urn:iauthsession:...
的 key 已添加到我的 Redis 服务器。但是所有具有 [Authenticate]
属性的路由都会出现 401 Unauthorized
错误。
CustomCredentialsAuthProvider
是这样实现的:
public class CustomCredentialsAuthProvider : CredentialsAuthProvider
{
public override bool TryAuthenticate(IServiceBase authService, string userName, string password)
{
if (userName != string.Empty && password != string.Empty)
{
// Database call ...
var session = (CustomSession)authService.GetSession();
session.ClientId = login.ClientId;
// Fill session...
authService.SaveSession(session, SessionExpiry);
return true;
}
return false;
}
}
ServiceStack 版本:3.9.71
编辑:
我试图覆盖 CredentialsAuthProvider
IsAuthorized
方法但没有成功。
但我从 AuthUserSession
继承我的 session 对象,它也有一个 IsAuthorized
方法。当我从此方法返回 true 时,Redis session 会使用 Authenticate
属性。
public class CustomSession : AuthUserSession
{
public int ClientId { get; set; }
...
public override bool IsAuthorized(string provider)
{
return true;
}
}
最佳答案
Authenticate
属性调用 AuthUserSession
类的 IsAuthorized
。
在我的例子中,为了让它与 Redis 缓存客户端一起工作,我做了以下操作
public override bool IsAuthorized(string provider)
{
string sessionKey = SessionFeature.GetSessionKey(this.Id);
ICacheClient cacheClient = AppHostBase.Resolve<ICacheClient>();
CustomUserSession session = cacheClient.Get<CustomUserSession>(sessionKey);
if (session == null)
{
return false;
}
return session.IsAuthenticated;
}
关于redis - 如何将我的自定义 ServiceStack 身份验证提供程序与 Redis 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20996856/