3

I have my configuration in web.config and it works fine.

  <configuration>
  <system.identityModel.services>
    <federationConfiguration>
....
 </federationConfiguration>
  </system.identityModel.services>
</configuration>

How do I move this out of web.config to a custom config file and load it from code?

I want to use the same structure of this configuration so that I do not have to change anything in code if I have to change this configuration file.

Birey
  • 1,764
  • 15
  • 20

1 Answers1

6

You can tap into the WIF event from your global.asax

void Application_Start(object sender, EventArgs e) 
{
    // Code that runs on application startup
    FederatedAuthentication.FederationConfigurationCreated += FederatedAuthenticationOnFederationConfigurationCreated;

}

In that handler you can adapt the configuration at runtime. Here is some code to give you an idea. The end code will be more complex.

   private void FederatedAuthenticationOnFederationConfigurationCreated(object sender, FederationConfigurationCreatedEventArgs args)
    {
        var identityConfiguration = new IdentityConfiguration(loadConfig:false);
        identityConfiguration.SecurityTokenHandlers.Clear();
        //...
        identityConfiguration.SecurityTokenHandlers.Add(new Saml2SecurityTokenHandler());
        //...
        var configuration = new FederationConfiguration(loadConfig: false)
        {
            CookieHandler = new ChunkedCookieHandler(),
            //...
            IdentityConfiguration = identityConfiguration
        };
        args.FederationConfiguration = configuration;
    }

If you have any doubts on what value to give to which object, you can always temporarily switch back to the configuration and inspect the runtime values through the same event. Don't underestimated the complexity and richness of the configuration delivered by WIF out of the box.
In general, you migth want a mixture of "code config" and "web.config config" were the web.config is still used to configure certain more variable parts of the config and the code is used for the more unchangable pieces...

  • Took a really long time to came to the conclusion to mark your answer correct. It wasn't what I was looking for at the time when I asked the question but now that I have implemented it and gone through all nuts and bolts of this(also used reflector plugin VS2013 to browse/debug framework code time and again) and my implementation almost looks like what you have given, your answer makes much sense now and hence marked right answer. – Birey Sep 09 '14 at 18:07
  • I never would have started here if not for the answer and the comment. This was very helpful. – Matthew David Jankowski Mar 23 '16 at 03:01