Search code examples
c#samlsaml-2.0assertion

Why Statements has only getter and can't be set through the only constructor in Saml2Assertion?


I need to set statements like attribute or authentication ones in SAML assertion but Microsoft.IdentityModel.Tokens.Saml2.Saml2Assertion doesn't allow to set Statements property neither via setter nor via the only constructor. Why is it so?


Solution

  • The .Statements property exposes a collection-type:

    using System.Collections.ObjectModel;
    using System.IdentityModel.Tokens;
    
    public Collection<Saml2Statement> Statements { get; }
    

    In the .NET world, collection-properties should always be implemented as get-only (aka readonly) properties. But the collection itself is still mutable.

    This rule is important, because it prevents whole classes of bugs caused by unexpected object reference changes (c.f. naive replaceable ObservableCollection<T> view-model references in WPF... yeah, I've been there too...).


    To add new statements, use the .Add method, or your friendly local .AddRange extension-method:

    Saml2Assertion              s2a          = ...
    IEnumerable<Saml2Statement> s2Statements = ...
    
    s2a.Statements.AddRange( s2Statements );