public override void OnAuthorization(AuthorizationContext filterContext) { if (string.IsNullOrEmpty(SessionPersister.Username)) { filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary( new { controller = "Account", action = "Index" })); } else { var service = System.Web.Mvc.DependencyResolver.Current.GetService(typeof(UserService)) as UserService; CustomPrincipal principal = new CustomPrincipal(service.GetByLogin(SessionPersister.Username)); //FormsAuthentication.SetAuthCookie(SessionPersister.Username, true); if (!principal.IsInRole(Roles)) { filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary( new { controller = "Account", action = "AccessDenied" })); } } }
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e) { HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName]; if (authCookie != null) { FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value); if (authTicket.Expired) { SessionPersister.Username = ""; return; } JavaScriptSerializer serializer = new JavaScriptSerializer(); CustomPrincipalSerializeModel serializeModel = serializer.Deserialize<CustomPrincipalSerializeModel>(authTicket.UserData); CustomPrincipal newUser = new CustomPrincipal(authTicket.Name); HttpContext.Current.User = newUser; SessionPersister.Username = serializeModel.Login; SessionPersister.Id = serializeModel.Id; SessionPersister.Email = serializeModel.Email; } }