我正在尝试按照此处的示例对 MVC 和 ServiceStack 进行身份验证 - https://github.com/ServiceStack/ServiceStack.UseCases/tree/master/CustomAuthenticationMvc。我的问题是,在我对帐户/登录的初始请求中,我无法针对 ServiceStack 成功进行身份验证。
AccountController的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。此外,这可能是也可能不是问题,但初始登录请求是由 MVC 处理的帐户/登录。因此,在 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 身份验证?
谢谢。