使用Active Directory在C#中进行身份验证

时间:2015-04-07 00:04:18

标签: c# security authentication active-directory

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

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

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

3 个答案:

答案 0 :(得分: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;

答案 1 :(得分:1)

使用.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);

答案 2 :(得分:1)

这取决于您使用的应用程序类型。 使用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的身份和访问工具