protected void Application_PostAuthenticateRequest(object sender, EventArgs e) { HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie != null) { FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); customPrincipalSerializeModel serializeModel = JsonConvert.DeserializeObject <customPrincipalSerializeModel>(authTicket.UserData); CustomPrincipal newUser = new CustomPrincipal(authTicket.Name); newUser.email = serializeModel.email; newUser.EID = serializeModel.EID; newUser.FirstName = serializeModel.FirstName; newUser.LastName = serializeModel.LastName; newUser.Role = serializeModel.Role; HttpContext.Current.User = newUser; } }
public async System.Threading.Tasks.Task<ActionResult> Login(employeeLogin login, string ReturnUrl = "") { if (ModelState.IsValid) { string message = ""; try { message = "Entered the try block"; using (HttpClient client = new HttpClient()) { client.BaseAddress = new Uri(BaseUrl); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/Json")); var json = JsonConvert.SerializeObject(login); var stringContent = new StringContent(json, Encoding.UTF8, "application/json"); var response = await client.PostAsync("Access", stringContent); if (response.IsSuccessStatusCode) { if (response.StatusCode == System.Net.HttpStatusCode.OK) { message = "Success Login"; var responseData = response.Content.ReadAsStringAsync().Result; var empData = JsonConvert.DeserializeObject<employee>(responseData); customPrincipalSerializeModel serializeEmployee = new customPrincipalSerializeModel(); serializeEmployee.email = empData.email; serializeEmployee.EID = empData.EID; serializeEmployee.FirstName = empData.fName; serializeEmployee.LastName = empData.lName; serializeEmployee.Role = empData.jobCategory; string accessData = JsonConvert.SerializeObject(serializeEmployee); int timeout = login.rememberMe ? 525600 : 10; //525600 min = 1 year var ticket = new FormsAuthenticationTicket(1, login.email, DateTime.Now, DateTime.Now.AddMinutes(timeout), true, accessData); string encrypted = FormsAuthentication.Encrypt(ticket); var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted); cookie.Expires = DateTime.Now.AddMinutes(timeout); cookie.HttpOnly = true; Response.Cookies.Add(cookie);// add cookie with the encrypted ticket if (Url.IsLocalUrl(ReturnUrl)) { return Redirect(ReturnUrl); } else { return RedirectToAction("Dashboard", "Home"); } } else if (response.Content.ReadAsStringAsync().Result == null) { message = " Wrong Email or Password"; } } else { message = "Wrong Email or Password "; } ViewBag.message = message; return View(); } } catch (Exception ex) { ViewBag.message = ex; return View(); } } else { return View(); } }