0
点赞
收藏
分享

微信扫一扫

Node.js 的 fs 模块和 path 模块的一些方法,以及第三方库 inquirer 和 ejs

 如题。使用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等

举报

相关推荐

0 条评论