[英]Cannot parse UserID from SAML 2.0 response XML
我正在嘗試使用onelogin.com C#示例中的示例應用程序,但它似乎有很多問題。 我剩下的最后一個問題是嘗試從SAML響應XML中解析諸如UserID之類的內容。 我似乎找不到在SAML中構建的.NET的任何示例C#代碼,因此我試圖使用原始XML工具來實現它,但是我從未與UserID匹配:
public string GetNameID()
{
XmlNamespaceManager manager = new XmlNamespaceManager(xmlDoc.NameTable);
manager.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl);
manager.AddNamespace("saml", "urn:oasis:names:tc:SAML:2.0:assertion");
manager.AddNamespace("samlp", "urn:oasis:names:tc:SAML:2.0:protocol");
XmlNode node = xmlDoc.SelectSingleNode("saml:Assertion/saml:Subject/saml:NameID", manager);
// node is now null!
return node.InnerText; // throws exception
}
這是我的(大量剪切的)XML,它刪除了所有不相關的節點/節:
<trust:RequestSecurityTokenResponseCollection xmlns:trust="http://docs.oasis-open.org/ws-sx/ws-trust/200512">
<trust:RequestSecurityTokenResponse>
<trust:RequestedSecurityToken>
<saml:Assertion xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion" Version="2.0" ID="pfxefe742da-7d6f-1f2a-85c6-0ab28c701748" IssueInstant="2016-06-14T12:14:56Z" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<saml:Subject>
<saml:NameID Format="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress">example@email.com</saml:NameID>
</saml:Subject>
</saml:Assertion>
</trust:RequestedSecurityToken>
</trust:RequestSecurityTokenResponse>
</trust:RequestSecurityTokenResponseCollection>
您可以使用LINQ to XML來搜索所需的標簽:
XDocument xmlDoc = XDocument.Load(xmlFilePath);
List<XElement> userIDs = (from element in xmlDoc.Descendants()
.Where(x => x.Name.LocalName.Contains("NameID"))
select element).ToList();
然后,您可以使用以下方式訪問用戶ID:
userIDs[index].Value;
或者,如果您想遍歷列表:
foreach (XElement element in userIDs)
{
element.Value; //Do something with this
}
不要忘記using System.Xml.Linq;
添加using System.Xml.Linq;
到文件頂部!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.