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

Posted by Your DisplayName here! on Least Privilege See other posts from Least Privilege or by Your DisplayName here!
Published on Thu, 02 Feb 2012 05:08:38 GMT Indexed on 2012/03/18 18:20 UTC
Read the original article Hit count: 313

Filed under:

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 SessionAuthenticationModule to 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.

© Least Privilege or respective owner

Related posts about IdentityModel