ASP.NET MVC - Set custom IIdentity or IPrincipal

后端 未结 9 1419
忘了有多久
忘了有多久 2020-11-21 23:06

I need to do something fairly simple: in my ASP.NET MVC application, I want to set a custom IIdentity / IPrincipal. Whichever is easier / more suitable. I want to extend the

9条回答
  •  自闭症患者
    2020-11-21 23:41

    Here is an example to get the job done. bool isValid is set by looking at some data store (lets say your user data base). UserID is just an ID i am maintaining. You can add aditional information like email address to user data.

    protected void btnLogin_Click(object sender, EventArgs e)
    {         
        //Hard Coded for the moment
        bool isValid=true;
        if (isValid) 
        {
             string userData = String.Empty;
             userData = userData + "UserID=" + userID;
             FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, username, DateTime.Now, DateTime.Now.AddMinutes(30), true, userData);
             string encTicket = FormsAuthentication.Encrypt(ticket);
             HttpCookie faCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encTicket);
             Response.Cookies.Add(faCookie);
             //And send the user where they were heading
             string redirectUrl = FormsAuthentication.GetRedirectUrl(username, false);
             Response.Redirect(redirectUrl);
         }
    }
    

    in the golbal asax add the following code to retrive your information

    protected void Application_AuthenticateRequest(Object sender, EventArgs e)
    {
        HttpCookie authCookie = Request.Cookies[
                 FormsAuthentication.FormsCookieName];
        if(authCookie != null)
        {
            //Extract the forms authentication cookie
            FormsAuthenticationTicket authTicket = 
                   FormsAuthentication.Decrypt(authCookie.Value);
            // Create an Identity object
            //CustomIdentity implements System.Web.Security.IIdentity
            CustomIdentity id = GetUserIdentity(authTicket.Name);
            //CustomPrincipal implements System.Web.Security.IPrincipal
            CustomPrincipal newUser = new CustomPrincipal();
            Context.User = newUser;
        }
    }
    

    When you are going to use the information later, you can access your custom principal as follows.

    (CustomPrincipal)this.User
    or 
    (CustomPrincipal)this.Context.User
    

    this will allow you to access custom user information.

提交回复
热议问题