Created
December 12, 2014 11:39
-
-
Save shelakel/48b572714b7dd7b49ed6 to your computer and use it in GitHub Desktop.
ASP.NET Identity 2.0 Identityless claims based authentication
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// App_Start/Startup.Auth.cs | |
public partial class Startup | |
{ | |
public void ConfigureAuth(IAppBuilder app) | |
{ | |
var cookieOptions = new CookieAuthenticationOptions { | |
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, | |
LoginPath = new PathString("/account/sign-in"), | |
Provider = new CookieAuthenticationProvider { | |
OnValidateIdentity = OnValidateIdentity | |
}, | |
ReturnUrlParameter = "returnUrl" | |
}; | |
app.UseCookieAuthentication(cookieOptions); | |
} | |
private static async Task OnValidateIdentity(CookieValidateIdentityContext vctx) | |
{ | |
int userId = 0; | |
byte[] securityStamp = null; | |
foreach (var claim in vctx.Identity.Claims) { | |
switch (claim.Type) { | |
case ClaimTypes.NameIdentifier: | |
Int32.TryParse(claim.Value, out userId); | |
break; | |
case ClaimTypes.Sid: | |
try { | |
securityStamp = Convert.FromBase64String(claim.Value); | |
} catch {} | |
break; | |
} | |
} | |
if (userId > 0 && securityStamp != null && securityStamp.Length > 0) { | |
using (var ctx = DependencyResolver.Current.GetService<IDbContextFactory<PMGContext>>().Create()) { | |
var user = await ctx.Users.GetByIdAsync(userId); | |
if (user != null && user.SecurityStampMatches(securityStamp)) { | |
return; | |
} | |
} | |
} | |
vctx.RejectIdentity(); | |
} | |
} | |
// BaseController to set claim identity | |
public abstract class BaseController : Controller | |
{ | |
protected IAuthenticationManager Authentication { get { return HttpContext.GetOwinContext().Authentication; } } | |
public int UserId | |
{ | |
get | |
{ | |
var userId = 0; | |
if (!User.Identity.IsAuthenticated) return userId; | |
if (Int32.TryParse(User.Identity.GetUserId(), out userId)) {} | |
return userId; | |
} | |
} | |
protected void SetIdentity(User user, bool rememberMe) | |
{ | |
var authProps = new AuthenticationProperties { | |
ExpiresUtc = DateTime.UtcNow.AddDays(7), | |
IsPersistent = rememberMe, | |
IssuedUtc = DateTime.UtcNow | |
}; | |
var identity = new ClaimsIdentity(DefaultAuthenticationTypes.ApplicationCookie); | |
identity.AddClaims(BuildUserClaims(user)); | |
identity.AddClaim(new Claim(ClaimTypes.IsPersistent, rememberMe.ToString())); | |
Authentication.SignIn(authProps, identity); | |
} | |
protected void RefreshIdentity(User user) | |
{ | |
var rememberMe = false; | |
var isPersistentClaim = ((ClaimsIdentity) User.Identity).Claims.FirstOrDefault(p => p.Type == ClaimTypes.IsPersistent); | |
if (isPersistentClaim != null && bool.TryParse(isPersistentClaim.Value, out rememberMe)) {} | |
SetIdentity(user, rememberMe); | |
} | |
private static IEnumerable<Claim> BuildUserClaims(User user) | |
{ | |
yield return new Claim(ClaimTypes.Name, string.Format("{0} {1}", user.FirstName, user.LastName)); | |
yield return new Claim(ClaimTypes.Email, user.EmailAddress); | |
yield return new Claim(ClaimTypes.NameIdentifier, user.Id.ToString(CultureInfo.InvariantCulture)); | |
yield return new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", user.Username); | |
yield return new Claim(ClaimTypes.Sid, Convert.ToBase64String(user.SecurityStamp)); | |
foreach (var role in user.Roles) { | |
yield return new Claim(ClaimTypes.Role, role.Name); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment