Skip to content

Instantly share code, notes, and snippets.

Created May 2, 2017 13:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ErikHen/5945cf31f37aeb2afd44c65d9f470a52 to your computer and use it in GitHub Desktop.
Save ErikHen/5945cf31f37aeb2afd44c65d9f470a52 to your computer and use it in GitHub Desktop.
Episerver Federated security
using System;
using System.Configuration;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web.Helpers;
using EPiServer.Cms.UI.AspNetIdentity;
using EPiServer.Security;
using EPiServer.ServiceLocation;
using Microsoft.Owin;
using Microsoft.Owin.Extensions;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.WsFederation;
using Owin;
[assembly: OwinStartup(typeof(MyNamespace.Web.Startup))]
namespace MyNamespace.Web
public class Startup
const string LogoutUrl = "/util/logout.aspx";
public void Configuration(IAppBuilder app)
// Add CMS integration for ASP.NET Identity
//federated authentication
app.UseCookieAuthentication(new CookieAuthenticationOptions
AuthenticationType = WsFederationAuthenticationDefaults.AuthenticationType
app.UseWsFederationAuthentication(new WsFederationAuthenticationOptions()
//URL to federation server meta data
MetadataAddress = "",
//Value of Wtrealm must *exactly* match what is configured in the federation server
Wtrealm = ConfigurationManager.AppSettings["AdfsWtRealm"],
Notifications = new WsFederationAuthenticationNotifications()
RedirectToIdentityProvider = (ctx) =>
//To avoid a redirect loop to the federation server send 403 when user is authenticated but does not have access
if (ctx.OwinContext.Response.StatusCode == 401 && ctx.OwinContext.Authentication.User.Identity.IsAuthenticated)
ctx.OwinContext.Response.StatusCode = 403;
return Task.FromResult(0);
SecurityTokenValidated = (ctx) =>
//Ignore scheme/host name in redirect Uri to make sure a redirect to HTTPS does not redirect back to HTTP
var redirectUri = new Uri(ctx.AuthenticationTicket.Properties.RedirectUri, UriKind.RelativeOrAbsolute);
if (redirectUri.IsAbsoluteUri)
ctx.AuthenticationTicket.Properties.RedirectUri = redirectUri.PathAndQuery;
//Sync user and the roles to EPiServer in the background
return Task.FromResult(0);
//Add stage marker to make sure WsFederation runs on Authenticate (before URL Authorization and virtual roles)
//Remap logout to a federated logout
app.Map(LogoutUrl, map =>
map.Run(ctx =>
return Task.FromResult(0);
//Tell antiforgery to use the name claim
AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.Name;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment