redis - 如何将我的自定义 ServiceStack 身份验证提供程序与 Redis 一起使用?

标签 redis servicestack servicestack-bsd servicestack-auth

我已经为我的身份验证实现了自定义 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/

相关文章:

authentication - 如何检查用户是否在 Service Stack Client 中经过身份验证?

servicestack - 最新版本的 ServiceStack 3 中是否存在构建问题?

c# - ServiceStack 3.9.71 中缺少类型

docker - Telegraf 在本地主机上的 Docker 容器上运行时如何监控 Grafana 上的 Redis 指标?

database - 用键值存储中的索引模拟数据库表的最简单方法是什么?

c# - 找不到 ServiceStack RequestContext

mysql - OrmLite(服务堆栈): Only use temporary db-connections (use 'using' ?)

docker - Redis 在 docker 容器中无故关闭

python - Redis中根据时间获取所有key

c# - ServiceStack 完整菜鸟教程