Last active
August 30, 2018 20:10
-
-
Save octaviordz/afa5291675cc3a7b0f1fd9fdbfe5e6e9 to your computer and use it in GitHub Desktop.
ASP.NET: How to create form authentication cookie and set HttpContext.User
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
[HttpGet] | |
public IHttpActionResult Authentication(string userName, string password) | |
{ | |
// Authenticate by any application specific logic, like calling to a a database and validating username and password | |
var appUser = DbAuthentication(userName, password); | |
SetAuthenticationCookie(appUser); | |
} | |
private static void SetAuthenticationCookie(Security.AppUser user) | |
{ | |
JObject data = new JObject(); | |
data["UserId"] = user.UserId; | |
data["FullName"] = user.FullName; | |
data["TokenId"] = user.TokenId; | |
data["Roles"] = new JArray(user.Roles); | |
var userData = data.ToString(Formatting.None); | |
FormsAuthenticationTicket tkt = new FormsAuthenticationTicket(1, user.UserName, DateTime.Now, DateTime.Now.AddMinutes(120), true, userData); | |
string cookiestr = FormsAuthentication.Encrypt(tkt); | |
HttpCookie ck = new HttpCookie(FormsAuthentication.FormsCookieName, cookiestr); | |
ck.Expires = tkt.Expiration; | |
ck.Path = FormsAuthentication.FormsCookiePath; | |
HttpContext.Current.Response.Cookies.Add(ck); | |
} |
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_AuthenticateRequest(object sender, EventArgs e) | |
{ | |
HttpCookie authCookie = Context.Request.Cookies[FormsAuthentication.FormsCookieName]; | |
string userId = null; | |
string fullName = null; | |
string tokenId = null; | |
string[] roles = null; | |
if (authCookie != null) | |
{ | |
var authTicket = FormsAuthentication.Decrypt(authCookie.Value); | |
if (authTicket.Version == 1) | |
{ | |
JObject data = JObject.Parse(authTicket.UserData); | |
userId = (string)data["UserId"]; | |
fullName = (string)data["FullName"]; | |
tokenId = (string)data["TokenId"]; | |
roles= data["Roles"].ToObject<string[]>(); | |
} | |
// Security.AppUser class must implement System.Security.Principal | |
Security.AppUser userPrincipal = new Security.AppUser( | |
new GenericIdentity(authTicket.Name), | |
fullName, | |
new Guid(userId), | |
new Guid(tokenId), | |
roles); | |
Context.User = userPrincipal; | |
//Now you can access current authenticated user by the User property in the controllers. HttpContext.User | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment