Created
May 13, 2011 19:31
-
-
Save briandonahue/971156 to your computer and use it in GitHub Desktop.
This file contains 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
// This would go in your authentication routine, if auth was successful | |
var jsonSerializer = new JavaScriptSerializer(); // or serialize however you wish | |
var ticket = new FormsAuthenticationTicket(1, username, DateTime.Now, DateTime.Now.AddHours(4), | |
false, | |
jsonSerializer.Serialize(user.AsPrincipal())); // converts my user object to a custom IPrincipal object (below) | |
cookieService.SetCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket)); | |
return true; //auth successful |
This file contains 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
protected void Application_OnPostAuthenticateRequest() | |
{ | |
var cookie = Request.Cookies[FormsAuthentication.FormsCookieName]; | |
if (cookie != null) | |
{ | |
var ticket = FormsAuthentication.Decrypt(cookie.Value); | |
var myPrincipal = jsonSerializer.Deserialize<MyPrincipal>(ticket.UserData); | |
Context.User = myPrincipal; | |
} | |
} |
This file contains 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
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Security.Principal; | |
namespace My.Infrastructure.Security | |
{ | |
public class MyPrincipal: IPrincipal | |
{ | |
public string Name { get; set; } | |
public IEnumerable<string> Roles { get; set; } | |
public MyPrincipal() {} | |
public MyPrincipal(string name, IEnumerable<string> roles) | |
{ | |
Name = name; | |
Roles = roles; | |
} | |
public bool IsInRole(string role) | |
{ | |
return Roles.Any(r => r == role); | |
} | |
public IIdentity Identity | |
{ | |
get { return new GenericIdentity(Name); } | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment