【问题标题】:How to store info about the authenticated user in WCF?如何在 WCF 中存储有关经过身份验证的用户的信息?
【发布时间】:2009-12-11 21:43:21
【问题描述】:

我有一个 WCF 服务,我在其中使用 customUserNamePasswordValidatorType(在 web.config 文件的 behavior\serviceBehaviors\serviceCredentials\userNameAuthentication 部分中指定)。

我的自定义 UserNamePasswordValidator 就是这样工作的:

public bool Authenticate(string userName, string password)
{
     If ( IsUserValid(username, password) )
    {
        UserInfo currentUser = CreateUserInfo(username);
       //
       // Here I'd like to store the currentUser object somewhere so that
       // it can be used during the service method execution
       //
       return true;
    }
    return false;

}

在服务调用执行期间,我需要访问经过身份验证的用户的信息。例如我希望能够实现:

public class MyService : IService
{
     public string Service1()
    { 
       //
       // Here I'd like to retrieve the currentUser object and use it
       //
       return "Hello" + currentUser.Name;
    }
}

我的问题是在身份验证过程中我应该如何以及在哪里存储信息,以便在调用执行过程中可以访问它?只要“会话”有效,该存储就应该持续。

顺便说一句,我不使用(也不想使用)安全会话和/或可靠会话。所以我同时关闭了建立安全上下文和可靠会话。

我正在考虑启用 ASP.NET 兼容模式以将用户信息存储在 HttpContext.Current.Session 中,但我觉得不应该这样做。

【问题讨论】:

    标签: wcf authentication


    【解决方案1】:

    将需要持久化的任何内容存储到持久存储中 - 例如数据库,这是最好的方法。

    将用户信息存储在用户表中,例如ASP.NET 会员系统或您自己的东西。保留某种识别令牌(用户名、ID 等),以便在需要时从数据库中检索该信息。

    您应该尽可能地努力拥有无状态的 WCF 服务 - 它不应该依赖于任何类型的“状态”,而不是安全地存储在数据库中的内容。

    【讨论】:

    • 好的,但是在服务执行过程中,如何获取当前用户的用户名以便在数据库中查找呢?
    • 您应该能够在每次服务调用中检查ServiceSecurityContext.Current.PrimaryIdentity。这应该包含当前经过身份验证的用户的 IIdentity
    • 该主要身份有一个“名称”属性,它应该是当前经过身份验证的用户的用户名;将其用作数据库表中更多用户信息的“入口点”
    • 非常感谢!我不知道ServiceSecurityContext.Current.PrimaryIdentity。事实上,我真的很想这样做。
    猜你喜欢
    • 1970-01-01
    • 2020-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-23
    • 2014-10-03
    • 1970-01-01
    相关资源
    最近更新 更多