Mixing Forms and Token Authentication in a single ASP.NET Application

I recently had the task to find out how to mix ASP.NET Forms Authentication with WIF’s WS-Federation. The FormsAuth app did already exist, and a new sub-directory of this application should use ADFS for authentication. Minimum changes to the existing application code would be a plus ;)

Since the application is using ASP.NET MVC this was quite easy to accomplish – WebForms would be a little harder, but still doable. I will discuss the MVC solution here.

To solve this problem, I made the following changes to the standard MVC internet application template:

  • Added WIF’s WSFederationAuthenticationModule and SessionAuthenticationModuleto the modules section.
  • Add a WIF configuration section to configure the trust with ADFS.
  • Added a new authorization attribute. This attribute will go on controller that demand ADFS (or STS in general) authentication.

The attribute logic is quite simple – it checks for authenticated users – and additionally that the authentication type is set to Federation. If that’s the case all is good, if not, the redirect to the STS will be triggered.

public class RequireTokenAuthenticationAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase
httpContext)
{
if
(httpContext.User.Identity.IsAuthenticated &&
httpContext.User.Identity.AuthenticationType.Equals(
WIF.
AuthenticationTypes.Federation, StringComparison
.OrdinalIgnoreCase))
{
return true
;
}

return false;
}

protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
// do the redirect to the STS
        var message = FederatedAuthentication.WSFederationAuthenticationModule.CreateSignInRequest(
“passive”,
filterContext.HttpContext.Request.RawUrl,
false
);
filterContext.Result =
new RedirectResult(message.RequestUrl);
}
}

That’s it ;) If you want to know why this works (and a possible gotcha) – read my next post.

This entry was posted in ASP.NET, IdentityModel. Bookmark the permalink.

3 Responses to Mixing Forms and Token Authentication in a single ASP.NET Application

  1. Pingback: Creating a custom Login page for federated authentication with Windows Azure ACS | A Cloudy Place

  2. runepetersen says:

    Thanks for this :)
    Is it possible to post what needs to be placed within the web.config? I am trying to get something very similar to what you’re describing here working and am having trouble getting MVC to play nice with WAAD

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s