ComponentPro UltimateSaml

Handling Exceptions

Language Filter: AllSend comments on this topic to ComponentPro

Handling Exceptions in UltimateSaml

SamlException can be thrown when using the library. We take an example below to show how to handle this exception:

Source Code

using System;
using System.Security.Cryptography.X509Certificates;
using ComponentPro.Saml;
using ComponentPro.Saml1;

...

static Assertion CreateAssertion()
{
    // Create a new instance of the Assertion class. 
    Assertion assertion = new Assertion();

    // Set Issuer 
    assertion.Issuer = "urn:test";
    // Set Conditions 
    assertion.Conditions = new Conditions(new TimeSpan(1, 0, 0));

    // Create an AuthenticationStatement. 
    AuthenticationStatement authenticationStatement = new AuthenticationStatement(AuthenticationMethodIdenfifiers.Password);
    NameIdentifier nameIdentifier = new NameIdentifier("urn:test", NameIdentifierFormats.X509SubjectName, "uid=test,ou=People,dc=test,dc=com");
    SubjectConfirmation subjectConfirmation = new SubjectConfirmation(ConfirmationMethods.Bearer);

    authenticationStatement.Subject = new Subject(nameIdentifier, subjectConfirmation);

    // Add the AuthenticationStatement to the Assertion. 
    assertion.Statements.Add(authenticationStatement);

    // Add attributes to the Assertion. 
    AttributeStatement attributeStatement = new AttributeStatement();

    attributeStatement.Subject = authenticationStatement.Subject;
    attributeStatement.Attributes.Add(new ComponentPro.Saml1.Attribute("email", "urn:test", "john@test.com"));
    attributeStatement.Attributes.Add(new ComponentPro.Saml1.Attribute("FirstName", "urn:test", "John"));
    attributeStatement.Attributes.Add(new ComponentPro.Saml1.Attribute("LastName", "urn:test", "Vu"));

    assertion.Statements.Add(attributeStatement);

    return assertion;
}

static void SignAssertion(Assertion assertion)
{
    // Load certificate to sign the assertion. 
    X509Certificate2 cert = new X509Certificate2("Pkey.pfx", "password");

    // Sign the assertion 
    assertion.Sign(cert);
}

static void ValidateAssertion(Assertion assertion)
{
    if (assertion.IsSigned())
    {
        bool result = assertion.Validate();

        if (result)
            System.Diagnostics.Trace.WriteLine("Assertion is validated");
        else 
            System.Diagnostics.Trace.WriteLine("Assertion cannot be validated");
    }
}

static void Main()
{
    try 
    {
        Assertion assertion = CreateAssertion();
        SignAssertion(assertion);

        ValidateAssertion(assertion);
    }
    catch (SamlException samlException)
    {
        // Handle the exception here. 
        // ... 
    }
}