如何验证ADFS SAML令牌

9

我目前是这样从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服务器的证书来解密令牌吗?

我可以把令牌保存到数据库中... - hoetz
2个回答

8
在查看了优秀的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; }
    }

}
}

我还添加了一些代码,将令牌转换为JWT,以便可以轻松地在Web请求中使用。 - hoetz
你需要将ADFS的令牌签名证书存储在本地以用于解密/读取令牌吗? - Developr

1
很简单!对于网站,您可以使用WIF(假设您正在使用.NET),然后将应用程序联合到ADFS。 (WIF SDK中包含向导)。一切都已经处理好了。框架会处理解析,验证等。您的应用程序将以常规方式处理用户:this.User.Namethis.User.IsInRole("admin")等。
该方案在此处有文档记录。

2
关于Web API怎么样?没有cookies,仅使用HTTP头信息。 - hoetz
取决于谁调用API以及API的实现方式。对于SOAP服务,您可以使用SAML和类似于您示例的调用。对于REST服务,您通常不会使用SAML,而是使用更轻量级的东西。如果您能扩展整个场景,那就太好了。 - Eugenio Pace

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接