【问题标题】:ServiceStack Authentication in standard MVC标准 MVC 中的 ServiceStack 身份验证
【发布时间】:2015-12-10 21:56:57
【问题描述】:

我有一个位于 MVC 项目的“api”位置的 ServiceStack API。除了这个 API,还有标准的 MVC 控制器和视图,它们使用 HostContext.ResolveService<MyService>(HttpContext) 调用 ServiceStack 服务。

我使用 ServiceStack AuthenticateService 设置了身份验证,调用 Authenticate(new Authenticate {...}) 方法然后设置 FormsAuthentication cookie。我没有在 web.config 中启用 FormsAuthentication 本身。这是 AppHost.cs 中的身份验证设置:

public void ConfigureAuth(Container container)
{
    var authFeature = new AuthFeature(() => new CustomUserSession(), new IAuthProvider[]
        {
            new BasicAuthProvider(), 
            new CredentialsAuthProvider()
        })
    {
        HtmlRedirect = "/Login",
        MaxLoginAttempts = 5,
        IncludeAssignRoleServices = false
    };
    Plugins.Add(authFeature);

    Register<IUserAuthRepository>(new OrmLiteAuthRepository(Resolve<IDbConnectionFactory>())
    {
        UseDistinctRoleTables = true
    });

    Resolve<IUserAuthRepository>().InitSchema();
}

在应用程序的初始运行中一切正常。未经身份验证的用户获得登录页面,它会登录,我可以提取会话数据,如名称和时区。我访问视图中的会话以使用以下代码填充菜单:

@{
    var key = SessionFeature.GetSessionKey() ?? "";
    var sess = HostContext.Resolve<ICacheClient>().Get<AuthUserSession>(key).ConvertTo<CustomUserSession>();
}
Welcome @sess.FirstName @sess.LastName

但是,一段时间后,会话似乎过期了,尽管我在上面提取的 ServiceStack 会话显示 true 对应于 IsAuthenticated,但其他会话数据(如名字/姓氏和时区)均无法访问。

因为我所说的时间段大约是 12 小时,所以我怀疑会话确实没有仍然经过身份验证。我尝试在 web.config 中启用 FormsAuthentication,但这搞砸了 api 端点,即使我在 location 部分下的 web.config 中排除了它。

有什么想法可能是错的吗?

【问题讨论】:

    标签: c# asp.net-mvc authentication servicestack


    【解决方案1】:

    IsAuthenticated=true 令人怀疑,但鉴于 ServiceStack session 只是序列化到已注册 Caching Provider 中的类型化 POCO,因此没有填充其他属性。我会检查底层缓存提供程序中的序列化值,看看是否真的如此。突出的一件事是,您在 AuthFeature 中指定了您正在使用的 CustomUserSession,但您却试图将其解析为 AuthUserSession,您需要使用相同的类型化会话。

    如果您将 MVC 与 ServiceStack 一起使用,建议您使用 inheriting ServiceStackController 的官方 API 解析会话,并使用以下方法在控制器中解析 ServiceStack 会话:

    var session = base.SessionAs<CustomUserSession>();
    

    【讨论】:

    • 在控制器中我这样做。问题是我试图用用户名填充的登录菜单位于_Layout.cshtml 页面中,因此无法从控制器中填充。我将更改调用以直接提取 CustomUserSession 而不是转换它,但该自定义会话中不存在相关属性(名字/姓氏)。
    • @Josh 你的CustomUserSession have DataContract attributes 吗?否则无法判断问题出在哪里,请检查会话键处缓存中序列化的原始字符串值。
    • 它没有...只是添加,并将监视它是否再次发生。谢谢,@mythz。仅供参考,在这里向 SS 客户付款,所以我非常感谢您的快速帮助:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-08
    • 2014-07-25
    • 1970-01-01
    • 2016-02-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多