且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何根据Active Directory联合身份验证服务(ADFS)验证用户名和密码?

更新时间:2023-12-01 08:07:46

以下代码对我有用

using System.IdentityModel.Tokens;
using Microsoft.IdentityModel.Protocols.WSTrust;
using System.ServiceModel;
using System.ServiceModel.Security;
using WSTrustChannel = Microsoft.IdentityModel.Protocols.WSTrust.WSTrustChannel;
using WSTrustChannelFactory = Microsoft.IdentityModel.Protocols.WSTrust.WSTrustChannelFactory;


namespace SOS.Tools.AdfsConnectionChecker

{
    internal class Token

    {

        public static SecurityToken GetToken(string username, string password, string tokenIssuer, string appliesTo, out RequestSecurityTokenResponse rsts)

        {
            WS2007HttpBinding binding = new WS2007HttpBinding();
            binding.Security.Message.EstablishSecurityContext = false;
            binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;
            binding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
            binding.Security.Mode = SecurityMode.TransportWithMessageCredential;


            var tokenIssuerUrlFormat = "https://{0}/adfs/services/trust/13/usernamemixed";
            var tokenIssuerUrl = string.Format(tokenIssuerUrlFormat, tokenIssuer);


            WSTrustChannelFactory trustChannelFactory =
                new WSTrustChannelFactory(binding, new EndpointAddress(tokenIssuerUrl));

            trustChannelFactory.TrustVersion = TrustVersion.WSTrust13;
            trustChannelFactory.Credentials.UserName.UserName = username;
            trustChannelFactory.Credentials.UserName.Password = password;

            trustChannelFactory.ConfigureChannelFactory();



            // Create issuance issuance and get security token 
            RequestSecurityToken requestToken = new RequestSecurityToken(WSTrust13Constants.RequestTypes.Issue);
            requestToken.AppliesTo = new EndpointAddress(appliesTo);

            WSTrustChannel tokenClient = (WSTrustChannel) trustChannelFactory.CreateChannel();
            SecurityToken token = tokenClient.Issue(requestToken, out rsts);
            return token;

        }

}

  • 用户名-域名用户名(例如 Name.FamalyName@DomainName.local )
  • 密码-域用户密码
  • tokenIssuer -ADFS URL( adfs.somedomain.com ).该ADFS应该连接到创建用户名的Active Directory
  • appliesTo -您想要令牌的应用(例如 https://apps.anydomain.com/WcfService1 ).必须在 tokenIssuer 上将其配置为Rellying Party.
    • username - Domain user name (e.g Name.FamalyName@DomainName.local)
    • password - Domain user password
    • tokenIssuer - ADFS URL (adfs.somedomain.com). That ADFS should be connected to Active Directory where username is created
    • appliesTo - Applicattion you want token for (e.g. https://apps.anydomain.com/WcfService1). It has to be configured on the tokenIssuer as Rellying Party.