.NET使用Microsoft.IdentityModel.Tokens对SAML2.0登录断言校验

 如题。使用SAML单点登录对IDP返回的Response断言使用微软提供的Microsoft.IdentityModel.Tokens对断言(Assertion)进行校验。

首先需要安装Muget包,Microsoft.IdentityModel.Tokens和Microsoft.IdentityModel.Tokens.Saml。

简易示例代码如下:

private X509SecurityKey GetSigningCertificate()
{
    //SAMLResponse ds:X509Data节点证书信息
    string samlCertificate = @"MIIC8DCCAdigAwIBAgIQY97pbBoha5tHlCRNbt64bjANBgkqhkiG9w0BAQsFADA0MTIwMAYDVQQDEylNaWNyb3NEiy9NIRqat894uFw2sxSlEe2zOSI1jBQVkI0qu/fAFEG/cK9/SMQ40f8/aLalWU6i2x5k3pslmuf1DN76mCIImBNxGBqtWKkRWZTuxbJ0zay70owDfS4JKsz";
    byte[] certBytes = Convert.FromBase64String(samlCertificate);
    X509Certificate2 certificate = new X509Certificate2(certBytes);
    //如果将证书安装在服务器,也可以调用证书,注意替换证书指纹
    // 加载用于验证签名的证书
    //var store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
    //store.Open(OpenFlags.ReadOnly);
    //var certs = store.Certificates.Find(X509FindType.FindByThumbprint, "证书指纹", false);
    //store.Close();

    //if (certs.Count == 0)
    //    throw new Exception("Signing certificate not found.");
    //var key = new X509SecurityKey(certs[0]);
    var key = new X509SecurityKey(certificate);
    return key;
}

public bool ValidateSamlAssertionSignature()
{
    string samlAssertion = Request.Form["SAMLResponse"].ToString();
    byte[] samlResponseBytes = Convert.FromBase64String(samlAssertion);

    // 将字节数组转换为 XML 文档
    XmlDocument samlResponseDoc = new XmlDocument();
    samlResponseDoc.Load(new MemoryStream(samlResponseBytes));

    // 从 SAML Response 中提取 Assertion 节点
    XmlNode assertionNode = samlResponseDoc.SelectSingleNode("//*[local-name()='Assertion' and namespace-uri()='urn:oasis:names:tc:SAML:2.0:assertion']");

    var tokenHandler = new Saml2SecurityTokenHandler();
    var validationParameters = new TokenValidationParameters
    {
        ValidateIssuer = true, // 根据需要设置
        ValidIssuer = "IDP提供的标识符",//Issuer节点
        ValidateAudience = false, // 根据需要设置
        ValidAudience= "你的EntityID",
        // 从证书存储中获取用于验证签名的证书
        IssuerSigningKey = GetSigningCertificate(),
        ValidateLifetime = true // 验证令牌是否在有效期内
        //以及其他校验点
    };

    try
    {
        //返回登录者信息,进行下一步处理
        ClaimsPrincipal securityToken = tokenHandler.ValidateToken(assertionNode.OuterXml, validationParameters, out var rawToken);
        var samlToken = rawToken as Saml2SecurityToken;

        // 验证成功,samlToken 包含断言信息,正常应该跳转到登录成功页面
        return true;
    }
    catch (SecurityTokenValidationException)
    {
        // 验证失败
        return false;
    }
}

也可以使用开源的saml库。比如AspNetSaml,ITfoxtec.Identity.Saml2以及Sustainsys.Saml2等

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值