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