如何在ASP.Net MVC控制器中正确使用ServiceStack身份validation
我在使用ServiceStack [Authentication]属性在ASP.Net MVC4控制器中工作时遇到问题,即使在正确提交登录详细信息之后,具有该属性的页面/操作方法也会将用户重定向到登录页面。
我遵循了SocialBootstrapApi示例,不同之处在于所有身份validationWeb服务调用都是从控制器进行的:
this.CreateRestClient().Post("/register", model);
到目前为止我做过的其他事情:
- 使用我自己的用户会话实现子类化AuthUserSession(与示例没有太大区别,但使用我自己的User表实现)
- 在我的BaseController上inheritanceServiceStackController,覆盖默认登录URL
- 使用我的用户会话实现在AppHost中启用Authfunction
注册确实有效,用户身份validation逻辑工作(即使会话不存在),我可以在请求中看到ss-id
和ss-pid
cookie。
所以我的完整问题清单:
- 如何使[Authenticate]属性起作用(或者,我做错了什么)?
- 如何在MVC控制器中保存和重用用户会话? 目前
this.UserSession
始终为null。 - 如何注销用户?
this.CreateRestClient().Get("/auth/logout");
似乎没有用。
更新1:
在我提交任何凭据之前,当我尝试加载安全页面(具有[Authenticate]属性的页面)时,会创建会话cookie( ss-id
和ss-pid
)。 这是预期的行为吗?
更新2:
我可以看到会话保存在MemoryCacheClient
,但尝试通过this.Cache.Get(SessionKey)
在基本控制器中检索它返回null(其中SessionKey如下: urn:iauthsession:1
)
经过多次摆弄后,显然挂钩ServiceStack身份validation的方法是通过以下方式调用AuthService:
try { authResponse = AuthService.Authenticate(new Auth{ UserName = model.UserName, Continue = returnUrl, Password = model.Password }); } catch (Exception ex) { // Cut for brevity... }
和NOT authResponse = this.CreateRestClient().Post
!
其中AuthService
在基本控制器中定义为:
public AuthService AuthService { get { var authService = ServiceStack.WebHost.Endpoints.AppHostBase.Instance.Container.Resolve(); authService.RequestContext = new HttpRequestContext( System.Web.HttpContext.Current.Request.ToRequest(), System.Web.HttpContext.Current.Response.ToResponse(), null); return authService; } }
其他一切(包括会话)现在正常工作。
您可以在ServiceStack用例存储库中找到它是如何完成的。 以下示例基于MVC4,但也适用于MVC3: CustomAuthenticationMvc 。