Partial Authentication with Azure Active Directory with WS Federation in an MVC Application

Given: an MVC web application that is authenticated with Azure Active Directory using WS Federation.

Problem: allow non-authenticated users to access the application, restrict some of the pages to authenticated users only.

Challenge: when you start a new project in Visual Studio 2013 and choose Azure Active Directory as your Identity provider you get a setup that is pre-configured to put the entire site behind authentication.

To re-configure your application to allow non-authenticated users, you will need to do the following:

Web.config
Change the authorization snippet to allow users.

<system.web>
    <authorization>
      <allow users="*" />
    </authorization>
	...
</system.web>

 
AccountController.cs
Add the SignIn Method

public ActionResult SignIn()
{
	if (Request.IsAuthenticated)
	{
		// Redirect to home page if the user is already signed in.
		return RedirectToAction("Index", "Home");
	}
	// Redirect to home page after signing in.	
	WsFederationConfiguration config = 
		FederatedAuthentication.FederationConfiguration
			.WsFederationConfiguration;

	string callbackUrl = 
		Url.Action("Index", "Home", 
			routeValues: null, protocol: Request.Url.Scheme);
		
	SignInRequestMessage signInRequest = 
		FederatedAuthentication.WSFederationAuthenticationModule
			.CreateSignInRequest(
				uniqueId: String.Empty,
				returnUrl: callbackUrl,
				rememberMeSet: false);

	signInRequest.SetParameter("wtrealm", IdentityConfig.Realm ?? config.Realm);
	return new RedirectResult(signInRequest.RequestUrl.ToString());
}

 
Now you can decorate the appropriate controllers and/or methods with the regular MVC [Authorize] attribute to require authentication.

 
If you have multiple Reply URLs configured for your application in Azure AD, you will need to add the following setting to your Web.config transforms for different environments:

<system.identityModel.services>
	<federationConfiguration>
		<wsFederation reply="EnvironmentSpecificReplyURL" 
				xdt:Transform="SetAttributes" />
	</federationConfiguration>
</system.identityModel.services>

 
Please view my subsequent blog post on how to handle 401 – Unauthorized errors properly.

 
Bonus Tip: consider switching your application from WS Federation to the newer and shinier OpenId Connect. See samples here.

Leave a Reply

Your email address will not be published. Required fields are marked *