【问题标题】:Authentication in C# with Active Directory在 C# 中使用 Active Directory 进行身份验证
【发布时间】:2015-04-07 00:04:18
【问题描述】:

我正在尝试创建一个需要通过 Active Directory 进行用户身份验证才能返回令牌的应用程序,但我不确定如何正确使用它。

我一直在查看Authenticate user by ADFS (Active Directory Federation Service),但我不确定如何创建请求安全令牌或如何正确使用它。

是否有任何可用的工作示例?任何帮助表示赞赏。

【问题讨论】:

    标签: c# security authentication active-directory


    【解决方案1】:

    这取决于您使用的是 WIF 还是 .NET 4.5 System.IdentityModel

    使用 WIF:

    string endpointUri = string.Format("https://{0}/adfs/services/trust/13/usernamemixed", _serverName);
    
    var factory = new Microsoft.IdentityModel.Protocols.WSTrust.WSTrustChannelFactory(
                  new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential),
                  new EndpointAddress(endpointUri));
    
    factory.TrustVersion = TrustVersion.WSTrust13;
    if (factory.Credentials != null)
    {
        factory.Credentials.UserName.UserName = "UserName";
        factory.Credentials.UserName.Password = "password";
    }
    
    var rst = new RequestSecurityToken
    {
        RequestType = WSTrust13Constants.RequestTypes.Issue,
        AppliesTo = new EndpointAddress(_relyingPartyUri),
        KeyType = WSTrust13Constants.KeyTypes.Bearer,
    };
    
    var channel = factory.CreateChannel();
    SecurityToken token = channel.Issue(rst);
    return token;
    

    【讨论】:

      【解决方案2】:

      使用 .NET 4.5 System.IdentityModel,您需要自己定义 UserNameWSTrustBinding:

      public class UserNameWSTrustBinding : WS2007HttpBinding
      {
          public UserNameWSTrustBinding()
          {
              Security.Mode = SecurityMode.TransportWithMessageCredential;
              Security.Message.EstablishSecurityContext = false;
              Security.Message.ClientCredentialType = MessageCredentialType.UserName;
          }
      }
      
      string endpointUri = string.Format("https://{0}/adfs/services/trust/13/usernamemixed", _serverName);
      
      var factory = new WSTrustChannelFactory(new UserNameWSTrustBinding(), endpointUri)
          {
              TrustVersion = TrustVersion.WSTrust13
          };
      
      factory.Credentials.UserName.UserName = "UserName";
      factory.Credentials.UserName.Password = "password";
      
      var rst = new RequestSecurityToken
      {
          RequestType = RequestTypes.Issue,
          AppliesTo = new EndpointReference(_relyingPartyUri),
          KeyType = KeyTypes.Symmetric
      };
      
      var channel = factory.CreateChannel();
      
      return channel.Issue(rst);
      

      【讨论】:

        【解决方案3】:

        这取决于您使用的应用程序类型。 使用 WIF 通过 ADFS 进行身份验证有两种形式: - 使用 Asp.net Web 表单或 MVC 的被动身份验证。可以参考这篇文章:Claims Aware MVC4 App using WIF Identity and Access tool in .Net 4.5

        此外,根据您使用的 .NET 框架,您还需要下载以下任一项: - 适用于 .NET 4.0 的 WIF 运行时和 WIF SDK - .NET 4.5 的身份和访问工具

        【讨论】: