如何在自己的客户端 - 服务器应用程序中使用System.IdentityModel

时间:2009-03-14 18:08:01

标签: c# wcf-security .net-3.0

我有一个基于TcpClient / TcpListener和SslStream的简单客户端 - 服务器应用程序。客户端可以使用X509Certificate对服务器进行身份验证,也可以在建立SslStream后发送用户名和密码。

WCF使用 System.IdentityModel 命名空间进行身份验证,但apparently可以在任意应用程序中使用 - 这听起来很有趣。有关如何做到这一点的信息很少(或者我今天的Google foo很弱)。

所以,我的问题是:我需要做什么才能将System.IdentityModel与我的应用程序集成?我不确定我是否需要所有的ClaimSet内容,但如果这样做会很好用户只需使用其Windows帐户或任何其他提供的身份验证机制即可登录。 (不幸的是我不能只是切换到WCF但必须使用自定义协议,尽管如果需要我可以对它进行一些更改。)

2 个答案:

答案 0 :(得分:17)

我的Google foo确实很弱。答案正好在我的问题中的链接背后。所以这里有一些this blog的链接,以防有人最终有同样的问题。

首先,您应该尝试理解“声明设置内容”:

然后,您需要知道声明集的来源:

有了这些知识,它实际上变得非常简单。

如果我理解正确,基本工作流程将是这样的:

  1. 客户使用SecurityToken
  2. 创建SecurityTokenProvider
  3. 客户端使用SecurityToken
  4. 序列化SecurityTokenSerializer
  5. 服务器使用SecurityToken
  6. 反序列化SecurityTokenSerializer
  7. 服务器使用IAuthorizationPolicy
  8. 创建SecurityTokenAuthenticator
  9. 服务器从AuthorizationContext s
  10. 创建IAuthorizationPolicy
  11. 完成
  12. 示例:

    // Create the SecurityTokenProvider
    var p = new UserNameSecurityTokenProvider("username", "password");
    
    // Get the SecurityToken from the SecurityTokenProvider
    var t = p.GetToken(TimeSpan.FromSeconds(1.0)) as UserNameSecurityToken;
    
    // ... transmit SecurityToken to server ...
    
    // Create the SecurityTokenAuthenticator
    var a = new CustomUserNameSecurityTokenAuthenticator(
        UserNamePasswordValidator.None);
    
    // Create IAuthorizationPolicies from SecurityToken
    var i = a.ValidateToken(t);
    
    // Create AuthorizationContext from IAuthorizationPolicies
    var c = AuthorizationContext.CreateDefaultAuthorizationContext(i);
    ShowClaims(c.ClaimSets);
    

    对于X509SecurityToken,请使用X509SecurityTokenProvider / Authenticator。对于WindowsSecurityToken,有WindowsSecurityTokenAuthenticator但不是提供者;相反,使用WindowsSecurityToken构造函数:

    var t = new WindowsSecurityToken(WindowsIdentity.GetCurrent());
    

    这很有效。到目前为止我唯一省略的是令牌序列化。有一个SecurityTokenSerializer类在.NET框架中有一个实现:WCF附带的WSSecurityTokenSerializer类。

    序列化UserNameSecurityTokenX509SecurityToken的工作方式类似于魅力(尚未尝试反序列化),但序列化程序显然不支持WindowsSecurityToken。这给我留下了我已经拥有的两种身份验证方法(证书和用户名/密码),而且,正如我不想要AuthorizationContext那样,我会坚持使用我所拥有的:)

答案 1 :(得分:7)

我没有在现有解决方案上发表评论的声誉,但我想将新网址发布到解决方案中列出的博客,因为这些不再适用。如果有人可以将此更改为评论,我将非常感激。