簡體   English   中英

如何驗證ADFS SAML令牌

[英]How to validate ADFS SAML token

我目前正在從ADFS生成SAML令牌,如下所示:

 WSTrustChannelFactory factory = null;
        try
        {
            // use a UserName Trust Binding for username authentication
            factory = new WSTrustChannelFactory(
                new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential),
                 new EndpointAddress("https://adfs.company.com/adfs/services/trust/13/usernamemixed"));

            factory.TrustVersion = TrustVersion.WSTrust13;

            factory.Credentials.UserName.UserName = "user";
            factory.Credentials.UserName.Password = "pw";


            var rst = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                AppliesTo = new EndpointReference(relyingPartyId),
                KeyType = KeyTypes.Bearer
            };
            IWSTrustChannelContract channel = factory.CreateChannel();
              GenericXmlSecurityToken genericToken = channel.Issue(rst) 
               as     GenericXmlSecurityToken;
         }
        finally
        {
            if (factory != null)
            {
                try
                {
                    factory.Close();
                }
                catch (CommunicationObjectFaultedException)
                {
                    factory.Abort();
                }
            }
        }

現在假設我構建了一個使用這些令牌進行身份驗證的Web應用程序。 據我所知,工作流程應該是這樣的:

  • 生成令牌
  • 客戶端獲取生成的令牌(有效登錄后)
  • 客戶端緩存令牌
  • 客戶端使用令牌進行下次登錄
  • Web應用程序驗證令牌,不必調用ADFS

如何驗證客戶端呈現的令牌是否有效? 我是否需要ADFS服務器的證書才能解密令牌?

在查看了優秀的thinktecture身份服務器代碼( https://github.com/thinktecture/Thinktecture.IdentityServer.v2/tree/master/src/Libraries/Thinktecture.IdentityServer.Protocols/AdfsIntegration )后,我解析了以下解決方案:

using Newtonsoft.Json;
using System;
using System.IdentityModel.Protocols.WSTrust;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Linq;
using System.Security.Claims;
using System.Security.Cryptography.X509Certificates;
using System.ServiceModel;
using System.ServiceModel.Security;
using System.Text;
using System.Xml;
using Thinktecture.IdentityModel.Extensions;
using Thinktecture.IdentityModel.WSTrust;

namespace SimpleWebConsole
{
internal class ADFS
{
    public static void tokenTest()
    {
        string relyingPartyId = "https://party.mycomp.com";
        WSTrustChannelFactory factory = null;
        try
        {
            // use a UserName Trust Binding for username authentication
            factory = new WSTrustChannelFactory(
                new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential),
                 new EndpointAddress("https://adfs.mycomp.com/adfs/services/trust/13/usernamemixed"));

            factory.TrustVersion = TrustVersion.WSTrust13;

            factory.Credentials.UserName.UserName = "test";
            factory.Credentials.UserName.Password = "test";

            var rst = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                AppliesTo = new EndpointReference(relyingPartyId),
                KeyType = KeyTypes.Bearer
            };
            IWSTrustChannelContract channel = factory.CreateChannel();
            GenericXmlSecurityToken genericToken = channel.Issue(rst) as GenericXmlSecurityToken; //MessageSecurityException -> PW falsch

            var _handler = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection();
            var tokenString = genericToken.ToTokenXmlString();

            var samlToken2 = _handler.ReadToken(new XmlTextReader(new StringReader(tokenString)));

            ValidateSamlToken(samlToken2);

            X509Certificate2 certificate = null;

            X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
            store.Open(OpenFlags.ReadOnly);
            certificate = store.Certificates.Find(X509FindType.FindByThumbprint, "thumb", false)[0];

            var jwt=ConvertSamlToJwt(samlToken2, "https://party.mycomp.com", certificate);

        }
        finally
        {
            if (factory != null)
            {
                try
                {
                    factory.Close();
                }
                catch (CommunicationObjectFaultedException)
                {
                    factory.Abort();
                }
            }
        }
    }

    public static TokenResponse ConvertSamlToJwt(SecurityToken securityToken, string scope, X509Certificate2 SigningCertificate)
    {
        var subject = ValidateSamlToken(securityToken);


        var descriptor = new SecurityTokenDescriptor
        {
            Subject = subject,
            AppliesToAddress = scope,
            SigningCredentials = new X509SigningCredentials(SigningCertificate),
            TokenIssuerName = "https://panav.mycomp.com",
            Lifetime = new Lifetime(DateTime.UtcNow, DateTime.UtcNow.AddMinutes(10080))
        };


        var jwtHandler = new JwtSecurityTokenHandler();
        var jwt = jwtHandler.CreateToken(descriptor);


        return new TokenResponse
        {
            AccessToken = jwtHandler.WriteToken(jwt),
            ExpiresIn = 10080
        };
    }


    public static ClaimsIdentity ValidateSamlToken(SecurityToken securityToken)
    {
        var configuration = new SecurityTokenHandlerConfiguration();
        configuration.AudienceRestriction.AudienceMode = AudienceUriMode.Never;
        configuration.CertificateValidationMode = X509CertificateValidationMode.None;
        configuration.RevocationMode = X509RevocationMode.NoCheck;
        configuration.CertificateValidator = X509CertificateValidator.None;

        var registry = new ConfigurationBasedIssuerNameRegistry();
        registry.AddTrustedIssuer("thumb", "ADFS Signing - mycomp.com");
        configuration.IssuerNameRegistry = registry;

        var handler = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection(configuration);
        var identity = handler.ValidateToken(securityToken).First();
        return identity;
    }

    public class TokenResponse
    {
        [JsonProperty(PropertyName = "access_token")]
        public string AccessToken { get; set; }


        [JsonProperty(PropertyName = "token_type")]
        public string TokenType { get; set; }


        [JsonProperty(PropertyName = "expires_in")]
        public int ExpiresIn { get; set; }


        [JsonProperty(PropertyName = "refresh_token")]
        public string RefreshToken { get; set; }
    }

}
}

它簡單得多! 對於網站,您使用WIF(假設您使用的是.NET),然后將應用程序與ADFS聯合起來。 (WIF SDK中包含一個向導)。 一切都得到了照顧。 解析,驗證等由框架完成。 您的應用程序將以常規方式處理用戶: this.User.Namethis.User.IsInRole("admin")等。

該方案記錄在此處

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM