服务堆栈用户会话不起作用

本文关键字:不起作用 会话 用户 堆栈 服务 | 更新日期: 2023-09-27 18:32:51

我有一个用ServiceStack编写的API,我正在尝试为客户端构建身份验证。目前,此API只能由Android客户端(Xamarin/C#)访问。API 本身运行在带有 Apache/mod_mono 的 Debian 服务器上

在阅读 Github 后,我仍然不是 100% 确定如何以这样的方式将它们放在一起......客户端提供有效凭据(用于测试,基本 HTTP 身份验证)后,用户将获得一个会话,并且不会在来自同一会话的后续请求中再次检查凭据。

应用主机类:

{
public class AppHost
    : AppHostBase
{       
    public AppHost() //Tell ServiceStack the name and where to find your web services
        : base("Service Call Service", typeof(ServiceCallsService).Assembly) { }
    public override void Configure(Funq.Container container)
    {
        //Set JSON web services to return idiomatic JSON camelCase properties
        ServiceStack.Text.JsConfig.EmitCamelCaseNames = true;
        // Session storage
        container.Register<ICacheClient>(new MemoryCacheClient());
        // auth feature and session feature
        Plugins.Add(new AuthFeature(
            () => new AuthUserSession(),
            new[] { new userAuth() }
        ) { HtmlRedirect = null } );
    }
    public class userAuth : BasicAuthProvider
    {
        public override bool TryAuthenticate(IServiceBase authService, string userName, string password)
        {
            peruseAuth peruseAuthHandler= new peruseAuth();
            errorLogging MyErrorHandler = new errorLogging() ; 
            if (peruseAuthHandler.ValidateUser(authService, userName, password))
            {
                try
                {
                    var session = (AuthUserSession)authService.GetSession(false);
                    session.UserAuthId = userName;
                    session.IsAuthenticated = true;
                    return true;
                }
                catch(Exception ex) 
                {
                   MyErrorHandler.LogError(ex, this) ;
                    return false ; 
                }
            }
            else
            {
                Console.Write("False");
                return false;
            }
        }
    }

JsonServiceClient:(只是"login"事件)

        btnLogin.Click += (sender, e) =>
            {
                // Set credentials from EditText elements in Main.axml
                client.SetCredentials(txtUser.Text, txtPass.Text);
                // Force the JsonServiceClient to always use the auth header
                client.AlwaysSendBasicAuthHeader = true;
            };

我一直在做一些日志记录,似乎每次客户端执行操作时,都会根据数据库检查他们的用户名/密码。这里有什么问题,还是这是预期的结果?

服务堆栈用户会话不起作用

对于基本身份验证,其中凭据在每个请求上发送,这是预期的。

为了使服务客户端保留已通过身份验证的会话 cookie,您应该在进行身份验证时设置 RememberMe 标志,例如使用 CredentialsAuthProvider:

var client = new JsonServiceClient(BaseUrl);
var authResponse = client.Send(new Authenticate {
    provider = "credentials", 
    UserName = "user",
    Password = "p@55word",
    RememberMe = true,
});

在后台,这会将用户会话附加到ss-pid cookie(永久会话 cookie),客户端保留该 cookie,并在来自该 ServiceClient 实例的后续请求时重新发送。