我正在尝试按照此处的示例 - https://github.com/ServiceStack/ServiceStack.UseCases/tree/master/CustomAuthenticationMvc对MVC和ServiceStack进行身份验证。 我的问题是,在我对Account / LogOn的初始请求中,我无法成功对ServiceStack进行身份验证。
var apiAuthService = AppHostBase.Resolve<AuthService>();
apiAuthService.RequestContext = System.Web.HttpContext.Current.ToRequestContext();
var apiResponse = apiAuthService.Authenticate(new Auth
{
UserName = model.UserName,
Password = model.Password,
RememberMe = false
});
我有一个自定义身份验证提供程序,它是CredentialsAuthProvider的子类。我在AppHost类中配置如下:
var appSettings = new AppSettings();
Plugins.Add(new AuthFeature(() => new CustomUserSession(),
new IAuthProvider[] {
new ActiveDirectoryAuthProvider(),
}));
public override bool TryAuthenticate(ServiceStack.ServiceInterface.IServiceBase authService, string userName, string password)
{
//class to authenticate against ActiveDirectory
var adAuthentication = new ActiveDirectoryAuthenticationService();
if (!adAuthentication.Authenticate(userName, password))
return false;
var session = (CustomUserSession)authService.GetSession(false);
session.IsAuthenticated = true;
session.UserAuthId = session.UserAuthName;
authService.SaveSession(session, SessionExpiry);
return true;
}
我认为我的问题是 session.Id 此时为空并且保存会话持续'urn:iauthsession:'到'SessionCache'。但是,我不确定如何正确填充 session.Id 。此外,这可能是也可能不是问题,但初始LogOn请求是由MVC处理的Account / Logon。因此,在AccountController中的AuthService.Authenticate()调用之前,没有ServiceStack请求。
我想出的一个可能的解决方案已经在我的CredentialsAuthProvider子类中添加了。
public override bool TryAuthenticate(ServiceStack.ServiceInterface.IServiceBase authService, string userName, string password)
{
//class to authenticate against ActiveDirectory
var adAuthentication = new ActiveDirectoryAuthenticationService();
if (!adAuthentication.Authenticate(userName, password))
return false;
var session = (CustomUserSession)authService.GetSession(false);
//A possible solution???
if(session.Id == null)
{
var req = authService.RequestContext.Get<IHttpRequest>();
var sessId = HttpContext.Current.Response.ToResponse().CreateSessionIds(req);
session.Id = sessId;
req.SetItem(SessionFeature.SessionId, sessId);
}
//end possible solution
session.IsAuthenticated = true;
session.UserAuthId = session.UserAuthName;
authService.SaveSession(session, SessionExpiry);
return true;
}
我是否缺少在MVC中“连接”ServiceStack身份验证的配置或调用?
感谢。
答案 0 :(得分:1)
我在TryAuthenticate中唯一要做的就是验证用户名,密码并在有效时返回true。
我有另一个名为OnAuthenticated的覆盖方法,我保存会话信息。 OnAuthenticated将Auth服务和Session作为参数传递,因此您只需:
public override void OnAuthenticated(IServiceBase authService, IAuthSession session,.....
{
session.IsAuthenticated = true;
session.....
authService.SaveSession(session, SessionExpiry);
}
只要我注册了ICacheClient,这似乎就存储了我的会话信息。