我有一个用ServiceStack编写的API,我正在尝试为客户端构建身份验证。目前,此API仅由Android客户端访问(Xamarin / C#)。 API本身在Apache / mod_mono
的Debian服务器上运行在阅读Github之后,我仍然不能100%确定如何将这些放在一起......一旦客户端提供了有效的凭据(用于测试,基本的HTTP身份验证),用户就会得到一个会话,在同一会话的后续请求中不会再次检查凭据。
AppHost类:
{
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: (只是“登录”事件)
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;
};
我一直在做一些日志记录,似乎每次客户端执行操作时,都会根据数据库检查用户名/密码。这里有什么问题,或者这是预期的结果吗?
答案 0 :(得分:1)
对于Basic Auth,其中的凭据是在每个请求上发送的。
为了让ServiceClient保留已经过身份验证的会话cookie,您应该在进行身份验证时设置RememberMe
标志,例如使用CredentialsAuthProvider:
var client = new JsonServiceClient(BaseUrl);
var authResponse = client.Send(new Authenticate {
provider = "credentials",
UserName = "user",
Password = "p@55word",
RememberMe = true,
});
Behind the scenes这会将用户会话附加到ss-pid
cookie(永久会话cookie),客户端会保留并重新发送来自该ServiceClient实例的后续请求。