自定义HttpContext.Current.User.Identity

在Global.asax中添加方法

 protected void Application_PostAuthenticateRequest(Object sender, EventArgs e) {
            HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];


            if (authCookie != null) {
                FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);


                var serializer = new JavaScriptSerializer();


                var serializeModel = serializer.Deserialize<CustomPrincipalSerializeModel>(authTicket.UserData);
                if (serializeModel != null) {
                    var newUser = new CustomPrincipal(HttpContext.Current.User.Identity);
                    newUser.TeacherId = serializeModel.TeacherId;
                    newUser.SchoolId = serializeModel.SchoolId;
                    // Consequently, when adding a custom principal in the PostAuthenticateRequest event we need to be certain to manually assign the Thread.CurrentPrincipal or else Thread.CurrentPrincipal and HttpContext.User will be out of sync
                    HttpContext.Current.User = newUser;
                    Thread.CurrentPrincipal = newUser; 

// Attach the CustomPrincipal to HttpContext.User and Thread.CurrentPrincipal
                }
            }
        }


Relevant  Class

 public class CustomPrincipal : IPrincipal
    {
        public IIdentity Identity { get; private set; }


        public bool IsInRole(string role)
        {
            return Roles.IsUserInRole(Identity.Name, role);
        }
   
        public CustomPrincipal(IIdentity identity)
        {   
            this.Identity = identity;
        }


        public int TeacherId { get; set; }
       
        public int SchoolId { get; set; }


        public bool? UseCustomScore { get; set; }


        public bool? UseCustomAsm { get; set; }


    }


    public class CustomPrincipalSerializeModel
    {
        public int TeacherId { get; set; }


        public int SchoolId { get; set; }


        public bool? UseCustomScore { get; set; }


        public bool? UseCustomAsm { get; set; }
    }


*-------------------------------For Login  part  ()*

 public virtual ActionResult Login(LoginModel model, string returnUrl)

{

 if (ModelState.IsValid && login-InvokedSuccessed)

{

 SaveCookie(model.Email);

}

}


private void SaveCookie(string username)
        {
            var teacher = _unityOfWork.TeacherRepository.GetByEmail(username);
            var school = _unityOfWork.SchoolRepository.GetById(teacher.SchoolId);
            var cookiemodel = new CustomPrincipalSerializeModel();
            cookiemodel.SchoolId = teacher.SchoolId;
            cookiemodel.TeacherId = teacher.TeacherId;
            cookiemodel.UseCustomScore = school.UseCustomScore;
            cookiemodel.UseCustomAsm = school.UseCustomAsm;


            var serializer = new JavaScriptSerializer();
            string userData = serializer.Serialize(cookiemodel);


            var authTicket = new FormsAuthenticationTicket(1, teacher.Email, DateTime.Now, DateTime.Now.AddHours(1),
                                                           false, userData);


            string encTicket = FormsAuthentication.Encrypt(authTicket);
            var faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
            Response.Cookies.Add(faCookie);


            //if (teacher.IsAdmin == null) teacher.IsAdmin = false;
            //var cookie = new HttpCookie("Teacher", teacher.SchoolId + "|" + teacher.TeacherId + "|" + teacher.IsAdmin);
            ////1 hour
            //cookie.Expires = DateTime.Now.AddHours(1);
            // HttpContext.Response.Cookies.Add(cookie);
        }

你可能感兴趣的:(自定义HttpContext.Current.User.Identity)