如何解析.NET中的SAML断言请求 [英] How to parse a SAML assertion request in .Net
问题描述
我想.NET实现一个SAML SSO解决方案,但我有一个问题,解析断言。
I'm trying to implement a SAML SSO solution in .Net, but I'm having a problem parsing the assertion.
我有一个样品的断言(看起来像字节[]
数据为文本)和相应的的.p7b
文件。
I have a sample assertion (looks like byte[]
data as text) and corresponding .p7b
file.
我想从的.p7b
加载密钥和解密断言为XML文档。
I want to load the keys from the .p7b
and decrypt the assertion to an XML document.
到目前为止,我认为我正确读取键:
So far I think I'm reading the keys correctly:
// get the key data
byte[] certificateData = System.IO.File.ReadAllBytes("myKeys.p7b");
// decode the keys
var cms = new SignedCms(SubjectIdentifierType.IssuerAndSerialNumber);
cms.Decode(certificateData);
var samlCertificates = cms.Certificates;
然后我尝试分析断言,我得到了一个问题:
Then I try to parse the assertion I get a problem:
// we have a keychain of X509Certificate2s, we need a collection of tokens
var certificatesAsTokens =
from X509Certificate2 cert in samlCertificates
select new X509SecurityToken(cert) as SecurityToken;
// get a token resolver
var tokens = new ReadOnlyCollection<SecurityToken>(
certificatesAsTokens.ToList());
var resolver = SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
tokens, true);
// get the SAML data in an XML reader
var reader = XmlReader.Create(assertionPostStream);
// use the WS Security stuff to parse the reader
var securityToken = WSSecurityTokenSerializer.
DefaultInstance.ReadToken(reader, resolver) as SamlSecurityToken;
这是最后一条语句抛出一个异常,指出它不能解析的XML内容。
That last statement throws an exception, stating that it can't parse the XML content.
我想这意味着我缺少的一个步骤解密断言 - 获得字节[]
文本转换为SAML格式的XML文档
I think this means that I'm missing a step decrypting the assertion - getting the byte[]
as text converted to a SAML format XML document.
任何人都知道如何添加这一步呢?我失去了什么东西?
Anyone know how to add this step? Am I missing something else?
推荐答案
我已经想通了这一点 - 我错过了SAML规范的一部分
I've figured this out - I was missing part of the SAML specification.
断言被发送(而古怪,因为它没有被加密)为base64数据,并将其作为地址连接$ C $光盘的两倍,因为它被发送
The assertion is sent (rather weirdly, since it isn't encrypted) as base64 data, and it was being URL encoded twice as it was sent.
所以,加入这一步给了我们一个有效的断言:
So adding this step gives us a valid assertion:
// spec says "SAMLResponse="
string rawSamlData = Request["SAMLResponse"];
// the sample data sent us may be already encoded,
// which results in double encoding
if (rawSamlData.Contains('%'))
{
rawSamlData = HttpUtility.UrlDecode(rawSamlData);
}
// read the base64 encoded bytes
byte[] samlData = Convert.FromBase64String(rawSamlData);
// read back into a UTF string
string samlAssertion = Encoding.UTF8.GetString(samlData);
借助认证仍无法工作的的,但是我现在有有效的XML所以这是一个不同的问题。
The authentication still isn't working, but I now have valid XML so it's a different problem.
这篇关于如何解析.NET中的SAML断言请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!