gpt4 book ai didi

c# - 从 SAML 断言中提取 SecurityToken

转载 作者:太空狗 更新时间:2023-10-30 00:42:19 25 4
gpt4 key购买 nike

我有一个 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 读取 token ,我会得到以下异常:

ID4075: SAML Assertion is missing the required 'MajorVersion' Attribute.

如果我尝试使用 Saml2SecurityTokenHandler 读取 token ,我会得到一个不同的异常:

Element 'Assertion' with namespace name 'urn:oasis:names:tc:SAML:2.0:assertion' was not found.

很明显,Saml2SecurityTokenHandler 是有意义的,因为这是一个 SAML 1.1 断言。但是,为什么 SAML 1.1 TokenHandler 不能读取这个断言?

编辑:读者似乎是空的;这是为什么? doc 有内容。

string notEmpty = doc.FirstNode.ToString();
string empty = doc.CreateReader().ReadOuterXml();

最佳答案

根据显示的技术绘制 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 文档中的空格,否则您将收到签名验证错误。

关于c# - 从 SAML 断言中提取 SecurityToken,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16287184/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com