在C#4.5(WIF)中使用断言创建SAML响应

时间:2017-04-19 11:51:08

标签: c# .net-4.5 saml-2.0 wif

我需要一种方法将<samlp:response>消息发送到某个URL,它相当简单,.NET可以帮助我Saml2Assertion类,但我似乎无法找到一种方法来包装该断言在回复中并将其序列化(甚至没有手动发布)?

Saml2Assertion assert = new Saml2Assertion(new Saml2NameIdentifier("SAMLIssuer"));
assert.Subject = new Saml2Subject(new Saml2NameIdentifier("10001", new Uri("urn:oasis:names:tc:SAML:2.0:nameid-format:persistent")));
Saml2AuthenticationContext context = new Saml2AuthenticationContext(new Uri("urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport"));
assert.Statements.Add(new Saml2AuthenticationStatement(context, DateTime.Now));

string assertion;
using (var sw = new StringWriter())
{
    var xws = new XmlWriterSettings();
    using (var xw = XmlWriter.Create(sw, xws))
    {
        var handler = new Saml2SecurityTokenHandler();
        handler.WriteToken(xw, new Saml2SecurityToken(assert));
    }
    assertion = sw.ToString();
}

我得到的用于断言的XML似乎很好:

<?xml version="1.0" encoding="utf-16"?>
<Assertion ID="_fc348927-c0bf-4955-b98f-483043d8dedd" IssueInstant="2017-04-19T11:29:38.464Z" Version="2.0" xmlns="urn:oasis:names:tc:SAML:2.0:assertion">
    <Issuer>SAMLIssuer</Issuer>
    <Subject>
        <NameID Format="urn:oasis:names:tc:SAML:2.0:nameid-format:persistent">10001</NameID>
    </Subject>
    <AuthnStatement AuthnInstant="2017-04-19T11:29:39.040Z">
        <AuthnContext>
           <AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport</AuthnContextClassRef>
        </AuthnContext>
    </AuthnStatement>
</Assertion>

那么,现在呢?如何从我的代码中获取:

<samlp:Response
    xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol"
    xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion"
    ID="new id"
    InResponseTo="old id"
    Version="2.0"
    IssueInstant="2017-04-19T11:29:39.040Z"
    Destination="some url">
    <saml:Issuer>SAMLIssuer</saml:Issuer>
    <samlp:Status>
      <samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/>
    </samlp:Status>
    <saml:Assertion ....

不使用外部库或制作我自己的包装/字符串连接?我似乎无法在.NET 4.5的WIF实现中找到任何可以帮助我的东西。

1 个答案:

答案 0 :(得分:3)

AFAIK .NET没有对SAMLp协议的内置支持。它只支持WsFederation。另请看这里:How should I implement SAMLP 2.0 in an ASP.NET MVC 4 service provider?