【问题标题】:Authentication in C# with Active Directory在 C# 中使用 Active Directory 进行身份验证
【发布时间】:2015-04-07 00:04:18
【问题描述】:
【问题讨论】:
标签:
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);