Record the understanding and use of FormsAuthentication

FormsAuthentication.SetAuthCookie() is to generate a client-side encrypted Cookie, which means that the authentication is passed. When the next visit requires authentication, the server will read the Cookie and perform authentication without going to the login page.
FormsAuthentication.RedirectFromLoginPage this is to go to the login page (no login)


Configure mode="Forms"
Insert picture description here

Login: There are two methods, both have the same effect, the latter can bring custom data

    //方法一
    FormsAuthentication.SetAuthCookie(customer.UserName, customer.IsRemember);

 
    //方法2,可以带自定义数据
    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, username, DateTime.Now, DateTime.Now.AddDays(1), true, "自定义数据","/");
    string hashTicket = FormsAuthentication.Encrypt(ticket);
    HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashTicket);
    cookie.HttpOnly = true;
    Response.Cookies.Add(cookie);

    //重定向至原始请求URL上
    string returnUrl = FormsAuthentication.GetRedirectUrl(username, false);
    if (!string.IsNullOrEmpty(returnUrl))
    {
    
    
        Response.Redirect(returnUrl);
    }

Log out, delete verification label
: Insert picture description here
The application display of the layout page, whether to log in to the application displayed by different labels:
Insert picture description here

Guess you like

Origin blog.csdn.net/MrLsss/article/details/106786425