我有SAML断言的XML,如下所示:
<saml:Assertion MajorVersion="1" MinorVersion="1" AssertionID="_9b6e6302-d6a8-47f0-9155-1051a05edbfb" Issuer="http://example.com/adfs/services/trust" IssueInstant="2013-04-29T19:35:51.197Z" xmlns:saml="urn:oasis:names:tc:SAML:1.0:assertion">
...
</saml:Assertion>
我正在尝试使用类似于以下内容的代码从此XML中获取SecurityToken:
// Loading the XML referenced above.
XDocument doc = XDocument.Load(new StringReader(assertion));
// Creating config to use in TokenHandlers below; required if not using a SecurityTokenHandlerCollection.
SecurityTokenHandlerConfiguration config = new SecurityTokenHandlerConfiguration();
config.AudienceRestriction.AllowedAudienceUris.Add(new Uri("https://localhost/Orchard/"));
config.CertificateValidator = X509CertificateValidator.None;
// Both of these lines throw Exceptions, as explained below.
new Saml11SecurityTokenHandler() { Configuration = config }.ReadToken(doc.CreateReader());
new Saml2SecurityTokenHandler() { Configuration = config }.ReadToken(doc.CreateReader());
如果我尝试使用Saml11SecurityTokenHandler
读取令牌,我会收到以下异常:
ID4075:SAML断言缺少必需的“MajorVersion”属性。
如果我尝试使用Saml2SecurityTokenHandler
读取令牌,我会得到一个不同的例外:
元素'断言',命名空间名称为'urn:oasis:names:tc:SAML:2.0:断言'未找到。
显然Saml2SecurityTokenHandler
的那个是有道理的,因为这是SAML 1.1断言。但是,为什么SAML 1.1 TokenHandler不能读取此断言?
编辑:读者似乎是空的;这是为什么? doc
有内容。
string notEmpty = doc.FirstNode.ToString();
string empty = doc.CreateReader().ReadOuterXml();
答案 0 :(得分:7)
根据here显示的技术,这有效:
SecurityToken token;
using (StringReader sr = new StringReader(assertion))
{
using (XmlReader reader = XmlReader.Create(sr))
{
if (!reader.ReadToFollowing("saml:Assertion"))
{
throw new Exception("Assertion not found!");
}
SecurityTokenHandlerCollection collection = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection();
token = collection.ReadToken(reader.ReadSubtree());
}
}
确保不要更改XML文档中的空格,否则您将收到签名验证错误。