c# - 如何验证 ADFS SAML token

标签 c# validation saml adfs

我目前正在像这样从 ADFS 生成 SAML token :

 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();
                }
            }
        }

现在假设我构建了一个使用这些 token 进行身份验证的 Web 应用程序。据我所知,工作流程应该是这样的:

  • 生成 token
  • 客户端获取生成的 token (在有效登录后)
  • 客户端缓存 token
  • 客户端下次登录使用token
  • 网络应用程序验证 token ,不必调用 ADFS

如何验证客户端提供的 token 是否有效?我需要 ADFS 服务器的证书来解密 token 吗?

最佳答案

在查看了出色的 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; }
    }

}
}

关于c# - 如何验证 ADFS SAML token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18701681/

相关文章:

asp.net-mvc - Azure AD SAML 身份验证 SP 启动

java - 如何将 Element 编码到 JAXB Axis2 响应对象

c# - C# 中 'on error goto [catch-all] label' 的现代方法

C# 如何将项目中的 jpeg 图像添加到图像数组中

validation - OmniFaces validateEquals 和复合组件

validation - Spring 3 - 在jsp 中访问messages.properties

saml - InvalidNameIDPolicy与ADFS一起使用

c# - WaitAll 与 WaitAny

c# - 如何显示两个表的搜索结果?

forms - form_widget不显示invalid_message错误