Mixed (Windows + Forms) Authentication for OWIN
OWIN middleware implementation mixing Windows and Forms Authentication.
PM> Install-Package OWIN-MixedAuth
Before running the samples, make sure to unlock windowsAuthentication
section:
Authentication - Windows
to Read/Write
windowsAuthentication
section and update overrideModeDefault
value to Allow
. <section name="windowsAuthentication" overrideModeDefault="Allow" />
Add reference to MohammadYounes.Owin.Security.MixedAuth.dll
Register MixedAuth
in Global.asax
//add using statement
using MohammadYounes.Owin.Security.MixedAuth;
public class MyWebApplication : HttpApplication
{
//ctor
public MyWebApplication()
{
//register MixedAuth
this.RegisterMixedAuth();
}
.
.
.
}
MixedAuth
in Startup.Auth.cs
//Enable Mixed Authentication
//As we are using LogonUserIdentity, its required to run in PipelineStage.PostAuthenticate
//Register this after any middleware that uses stage marker PipelineStage.Authenticate
app.UseMixedAuth(cookieOptions);
Important! MixedAuth is required to run in PipelineStage.PostAuthenticate
, make sure the use statement is after any other middleware that uses PipelineStage.Authenticate
. See OWIN Middleware in the IIS integrated pipeline.
<!-- Enable Mixed Auth -->
<location path="MixedAuth">
<system.webServer>
<security>
<authentication>
<windowsAuthentication enabled="true" />
</authentication>
</security>
</system.webServer>
</location>
Important! Enabling windows authentication for a sub path requires windowsAuthentication
section to be unlocked at a parent level.
Adding custom claims in OWIN-MixedAuth is pretty straightforward, simply use MixedAuthProvider
and place your own logic for fetching those custom claims.
The following example shows how to import user Email, Surname and GiveName from Active Directory:
// Enable mixed auth
app.UseMixedAuth(new MixedAuthOptions()
{
Provider = new MixedAuthProvider()
{
OnImportClaims = identity =>
{
List<Claim> claims = new List<Claim>();
using (var principalContext = new PrincipalContext(ContextType.Domain)) //or ContextType.Machine
{
using (UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(principalContext, identity.Name))
{
if (userPrincipal != null)
{
claims.Add(new Claim(ClaimTypes.Email, userPrincipal.EmailAddress ?? string.Empty));
claims.Add(new Claim(ClaimTypes.Surname, userPrincipal.Surname ?? string.Empty));
claims.Add(new Claim(ClaimTypes.GivenName, userPrincipal.GivenName ?? string.Empty));
}
}
}
return claims;
}
}
}, cookieOptions);