Ok this has taken me days to work out but these were the things I did to get it running. There is much more to do.
Prerequisites:
- An ADFS 2.0 service running somewhere on your domain.
- IIS 7 with a self signed certificate or a certificate that you can use across your domain.
- Visual Studio 2012 with the Identity and Access (version 1.0.2) Extension installed.
- A MVC4 web application set to run on IIS.
- Ensure that Self Signed Certificate is added to the site so you can access it via https.
- You may have to tweak the firewall settings of you machines to allow access to your ADFS 2.0 service.
On the Development Workstation
In your MVC4 Project
- Open up the Identity and Access Dialog by right-clicking your web project.
- Choose Use a business identity provider (e.g. ADFS2)
- Enter the path to the STS metadata document e.g. https://{PATH TO ADFS SERVER}/FederationMetadata/2007-06/FederationMetadata.xml
- Enter the realm for your application e.g. https://{WEB APPLICATION URL}/
- The trailing slash makes a difference.
- Exit the dialog by accepting these changes.
Add the following code to your project
using System;
using System.IdentityModel.Services;
namespace NAMESPACE
{
public class FixedWsFederationAuthenticationModule : WSFederationAuthenticationModule
{
public override void RedirectToIdentityProvider(string uniqueId, string returnUrl, bool persist)
{
//This corrects WIF error ID3206 "A SignInResponse message may only redirect within the current web application:"
//First Check if the request url doesn't end with a "/"
if (!returnUrl.EndsWith("/"))
{
//Compare if Request Url +"/" is equal to the Realm, so only root access is corrected
//https://localhost/AppName plus "/" is equal to https://localhost/AppName/
//This is to avoid MVC urls
if (String.Compare(System.Web.HttpContext.Current.Request.Url.AbsoluteUri + "/", base.Realm, StringComparison.InvariantCultureIgnoreCase) == 0)
{
//Add the trailing slash
returnUrl += "/";
}
}
base.RedirectToIdentityProvider(uniqueId, returnUrl, persist);
}
}
}
On the ADFS 2.0 Server
- If you used a self signed certificate navigate to your web application https://{WEB APPLICATION URL}/ and change the zone to trusted site.
- In the address bar of the browser you should be able to right click on the certificate and install (you can only install Certificates from trusted sites) The certificate needs to be installed under Trusted Root Authorities -> Registry,
- Open the ADFS Console, add Relying Party Trusts, with Federated Metadata address https://{WEB APPLICATION URL}/FederationMetadata/2007-06/FederationMetadata.xml
Add some custom rules
MVC4 needs these rules in order to make a usable ClaimsPrincipal
Add a pass-through rule on the Name property.
And these 2 custom rules
=> issue(Type = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", Value = "true");
=> issue(Type = "http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", Value = "true");