Skip to content

Instantly share code, notes, and snippets.

@briandonahue
Created May 13, 2011 19:31
Show Gist options
  • Save briandonahue/971156 to your computer and use it in GitHub Desktop.
Save briandonahue/971156 to your computer and use it in GitHub Desktop.
// 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
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;
}
}
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