我在让 ServiceStack [Authentication] 属性在 ASP.Net MVC4 Controller 中工作时遇到问题,即使在正确提交登录详细信息后,具有该属性的页面/操作方法仍将用户重定向到登录页面。
我遵循了 SocialBootstrapApi 示例,不同之处在于所有身份验证 Web 服务调用都是从 Controller 进行的:
this.CreateRestClient().Post<RegistrationResponse>("/register", model);
到目前为止我做过的其他事情:
- 使用我自己的用户 session 实现子类化 AuthUserSession(与示例没有太大区别,但使用我自己的用户表实现)
- 在我的 BaseController 上继承 ServiceStackController,覆盖默认登录 URL
- 通过我的用户 session 实现在 AppHost 中启用身份验证功能
注册确实有效,用户身份验证逻辑有效(即使 session 不会持续存在),我可以看到 ss-id
和 ss-pid
请求中的 cookie。
所以我的完整问题列表:
- 如何使 [Authenticate] 属性起作用(或者,我做错了什么)?
- 如何在 MVC Controller 中保存和重用用户 session ?此刻
this.UserSession
始终为空。 - 如何注销用户?
this.CreateRestClient().Get<AuthResponse>("/auth/logout");
似乎不起作用。
更新 1:
session cookie(ss-id
和 ss-pid
)在我尝试加载安全页面(具有 [Authenticate] 属性的页面)时创建,然后再提交任何凭据。这是预期的行为吗?
更新 2:
我可以看到 session 保存在 MemoryCacheClient
中,但是试图通过 this.Cache.Get<CustomUserSession>(SessionKey)
在基本 Controller 中检索它返回 null(其中 SessionKey 类似于:urn:iauthsession:1
)
最佳答案
经过多次尝试,显然 Hook ServiceStack 身份验证的方法是通过以下方式调用 AuthService:
try {
authResponse = AuthService.Authenticate(new Auth{ UserName = model.UserName, Continue = returnUrl, Password = model.Password });
} catch (Exception ex) {
// Cut for brevity...
}
和不 authResponse = this.CreateRestClient().Post<AuthResponse>("/auth/credentials", model);
!
在哪里AuthService
在基本 Controller 中定义为:
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;
}
}
其他所有内容(包括 session )现在都可以正常工作。
关于c# - 如何在 ASP.Net MVC Controller 中正确使用 ServiceStack 认证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12064166/