ASP.NET - ADFS authentication hook

167 Views Asked by At

I have an ASP.NET web API that authenticates against the ADFS server. The Authentication startup class is defined as below:

public void ConfigureAuth(IAppBuilder app)

{

    app.UseCookieAuthentication(
        new CookieAuthenticationOptions
        {
        AuthenticationType = WsFederationAuthenticationDefaults.AuthenticationType
        });

    app.UseWsFederationAuthentication(
        new WsFederationAuthenticationOptions
        {
            MetadataAddress = ConfigurationManager.AppSettings["ADFSMetadata"],
            Wtrealm = ConfigurationManager.AppSettings["Wtrealm"]
        });


    app.SetDefaultSignInAsAuthenticationType(WsFederationAuthenticationDefaults.AuthenticationType);

}

What I want is that when a user is successfully authenticated by the ADFS and the token is returned back, a user record in my SQL database should be created if the email found in the claim returned by ADFS does not exist in the database already.

Is there some way to intercept the response straight after the authentication to achieve the above task?

1

There are 1 best solutions below

0
A J Qarshi On BEST ANSWER

I have found a solution. The WsFederationAuthenticationOptions class has a Notification property which can be used to hook the authentication success and failure responses.

For example

public void ConfigureAuth(IAppBuilder app)

{

    app.UseCookieAuthentication(
        new CookieAuthenticationOptions
        {
        AuthenticationType = WsFederationAuthenticationDefaults.AuthenticationType
        });

    app.UseWsFederationAuthentication(
        new WsFederationAuthenticationOptions
        {
            MetadataAddress = ConfigurationManager.AppSettings["ADFSMetadata"],
            Wtrealm = ConfigurationManager.AppSettings["Wtrealm"],
            Notifications = new WsFederationAuthenticationNotifications
            {
                AuthenticationFailed = context =>
                {
                    context.HandleResponse();
                    context.Response.Redirect("/Error?message=" + context.Exception.Message);
                    return Task.FromResult(0);
                },
                SecurityTokenReceived = context =>
                {
                    // Get the token
                    var token = context.ProtocolMessage.GetToken();                    
                    return Task.FromResult(0);
                }
            }
        });


    app.SetDefaultSignInAsAuthenticationType(WsFederationAuthenticationDefaults.AuthenticationType);

}