c# - 如何在 ASP.Net MVC Controller 中正确使用 ServiceStack 认证

标签 c# authentication forms-authentication asp.net-mvc-4 servicestack

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

我遵循了 SocialBootstrapApi 示例,不同之处在于所有身份验证 Web 服务调用都是从 Controller 进行的:

this.CreateRestClient().Post<RegistrationResponse>("/register", model);

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

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

注册确实有效,用户身份验证逻辑有效(即使 session 不会持续存在),我可以看到 ss-idss-pid请求中的 cookie。

所以我的完整问题列表:

  1. 如何使 [Authenticate] 属性起作用(或者,我做错了什么)?
  2. 如何在 MVC Controller 中保存和重用用户 session ?此刻this.UserSession始终为空。
  3. 如何注销用户? this.CreateRestClient().Get<AuthResponse>("/auth/logout");似乎不起作用。

更新 1:
session cookie(ss-idss-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/

相关文章:

javascript - 从回调中访问 jwtFromRequest

forms-authentication - 自定义.NET身份验证,成员身份,Portlet的概要文件提供程序?

c# - Log4Net 多个项目

c# - linq 和字符串数组

javascript - 无法发布操作

php - 使用 Google 登录 Api 时如何在数据库中安全地插入和使用用户信息

asp.net - 仅允许特定 Web 用户对文件夹进行写访问

c# - ASP.NET 4.5 C# Forms 身份验证访问拒绝登录页面

c# - float.TryParse 忽略小数点

c# - 如何使用 Entity Framework 对 LocalDB 表进行 RESEED?