如何在ASP.Net MVC控制器中正确使用ServiceStack身份验证

hha*_*oko 14 c# authentication forms-authentication servicestack asp.net-mvc-4

我在使用ServiceStack [Authentication]属性在ASP.Net MVC4控制器中工作时遇到问题,即使在正确提交登录详细信息之后,具有该属性的页面/操作方法也会将用户重定向到登录页面.

我遵循了SocialBootstrapApi示例,区别在于所有身份验证Web服务调用都是从控制器进行的:

this.CreateRestClient().Post<RegistrationResponse>("/register", model);
Run Code Online (Sandbox Code Playgroud)

到目前为止我做过的其他事情:

  • 使用我自己的用户会话实现子类化AuthUserSession(与示例没有太大区别,但使用我自己的User表实现)
  • 在我的BaseController上继承ServiceStackController,覆盖默认登录URL
  • 使用我的用户会话实现在AppHost中启用Auth功能

注册确实有效,用户身份验证逻辑工作(即使会话不存在),我可以在请求中看到ss-idss-pidcookie.

所以我的完整问题列表:

  1. 如何使[Authenticate]属性起作用(或者,我做错了什么)?
  2. 如何在MVC控制器中保存和重用用户会话?目前this.UserSession总是空的.
  3. 如何注销用户?this.CreateRestClient().Get<AuthResponse>("/auth/logout");似乎不起作用.

更新1:在我提交任何凭据之前,当我尝试加载安全页面(具有[Authenticate]属性的页面)时,会创建
会话cookie(ss-idss-pid).这是预期的行为吗?

更新2:
我可以看到会话保存在MemoryCacheClient,但试图在主控制器通过检索它this.Cache.Get<CustomUserSession>(SessionKey)返回null(其中SessionKey是这样的:urn:iauthsession:1)

hha*_*oko 6

经过多次摆弄后,显然挂钩ServiceStack身份验证的方法是通过以下方式调用AuthService:

try {
    authResponse = AuthService.Authenticate(new Auth{ UserName = model.UserName, Continue = returnUrl, Password = model.Password });
} catch (Exception ex) {
    // Cut for brevity...
}
Run Code Online (Sandbox Code Playgroud)

不是 authResponse = this.CreateRestClient().Post<AuthResponse>("/auth/credentials", model);!

其中AuthService在基本控制器所限定:

public AuthService AuthService
{
    get
    {
        var authService = ServiceStack.WebHost.Endpoints.AppHostBase.Instance.Container.Resolve<AuthService>();
        authService.RequestContext = new HttpRequestContext(
            System.Web.HttpContext.Current.Request.ToRequest(),
            System.Web.HttpContext.Current.Response.ToResponse(),
            null);

        return authService;
    }
}
Run Code Online (Sandbox Code Playgroud)

其他一切(包括会话)现在正常工作.