The Visual Studio new project template is a handy wizard for setting up AD FS on a new site, but the wizard isn’t available for existing sites. Additionally, the wizard forces you to include ASP.NET MVC components, even if you just need to set up a Web API back-end. This post shows you how to do this manually.
-
Make sure SSL is enabled in your project.
-
Set The SSL URL to the one provided by your AD FS administrator, or configure AD FS to use your website url/port. e.g.
https://localhost:44300/
- Add required packages (search for these on NuGet)
Microsoft.Owin
Microsoft.Owin.Security
Microsoft.Owin.Security.Cookies
Microsoft.Owin.Security.WsFederation
Microsoft.Owin.Host.SystemWeb
- Add AD FS Metadata to
Web.config
<appSettings>
<add key="ida:ADFSMetadata" value="https://example.com/federationmetadata/2007-06/federationmetadata.xml" />
<add key="ida:Wtrealm" value="https://localhost:44300/" />
</appSettings>
-
Add a
Startup.cs
file/class if it does not already exist -
Add configuration hooks to
Startup.cs
. Note that if you have not addedMicrosoft.Owin.Host.SystemWeb
to your packagesStartup.Configuration()
will not fire.
public void Configuration(IAppBuilder app)
{
ConfigureAuth(app);
}
private void ConfigureAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseWsFederationAuthentication(
new WsFederationAuthenticationOptions
{
Wtrealm = ConfigurationManager.AppSettings["ida:Wtrealm"],
MetadataAddress = ConfigurationManager.AppSettings["ida:ADFSMetadata"]
});
}
- Add Authorization to controllers / routes.
-
Method 1: Set global filter
public static void Register(HttpConfiguration config) { ... // Authorize all api routes config.Filters.Add(new AuthorizeAttribute()); ... }
-
Method 2: Add Authorize Attribute to controller
[Authorize] public class PersonController : ApiController { ... }
-
- Build and Run your app. Your routes requiring authorization should now redirect you to the AD FS login page