开发者

Cookie quickly die

开发者 https://www.devze.com 2023-04-11 14:03 出处:网络
I have problem with cookie at server. Cookie quickly die. At localhostcookie good work. But the strangeness of the other. Itself cookie is present, but that code does not see it

I have problem with cookie at server. Cookie quickly die. At localhost cookie good work. But the strangeness of the other. Itself cookie is present, but that code does not see it

For create cookie I used this code

    public void SignIn(BaseUser user, bool isRememberMe)
    {
        string data = string.Format("{0},{1}, {2}", user.Id, user.Role.RoleName, user.Role.IsSuperRole);
        if (string.IsNullOrEmpty(user.UserName))
        {
            throw new ArgumentException("Error", "userName");
        }

        var ticket = new FormsAuthenticationTicket(
            1,
            user.UserName,
            DateTime.Now.ToLocalTime(),
            DateTime.Now.ToLocalTime().AddDays(30),
            isRememberMe,
            data,
            FormsAuthentication.FormsCookiePath);

        var encryptedTicket = FormsAuthentication.Encrypt(ticket);

        var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
            {
                HttpOnly = true,
                Secure = FormsAuthentication.RequireSSL,
                Path = FormsAuthentication.FormsCookiePath,
            };

        if (FormsAuthentication.CookieDomain != null)
        {
            cookie.Domain = FormsAuthentication.CookieDomain;
        }

        HttpContext.Current.Response.Cookies.Add(cookie);
    }

For read and change cookie, I use this code

    protected void Application_AuthenticateRequest(Object sender, EventArgs e)
    {
        HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
     开发者_JS百科   Identity id = null;

        if (authCookie != null)
        {
            FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
            id = this.GetUserIdentity(authTicket);
            authCookie.Expires = DateTime.Now.AddDays(30);
            HttpContext.Current.Response.Cookies.Add(authCookie);
        }
        else
        {
            id = new Identity();
        }

        var user = new Principal(id, id.RoleName);
        Context.User = user;
    }

    private Identity GetUserIdentity(FormsAuthenticationTicket ticket)
    {
        string[] userDetal = ticket.UserData.Split(Convert.ToChar(","));
        int id = int.Parse(userDetal[0]);
        string roleName = userDetal[1];
        bool isSuperRole;
        bool.TryParse(userDetal[2], out isSuperRole);
        string userName = ticket.Name;

        return new Identity(id, userName, true, isSuperRole, roleName);
    }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号