FormsAuthentication. SetAuthCookie & amp; FormsAuthentication. RedirectFromLoginPage, setauthcookie

Source: Internet
Author: User
Tags asp net

FormsAuthentication. SetAuthCookie & FormsAuthentication. RedirectFromLoginPage, setauthcookie

Let's take a look at the description of FormsAuthentication. SetAuthCookie.

Reference: http://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication.setauthcookie.aspx

Creates an authentication ticket for the supplied user name and adds it to the cookies collection of the response, or to the URL if you are using cookieless authentication.

Create an authentication credential for a provided user name and add it to the cookies collection of the response Request response (or add it to the response URL due to a lack of cookies)

My English is so bad that everyone can laugh at it.

  Name Description
SetAuthCookie (String, Boolean) Creates an authentication ticket for the supplied user name and adds it to the cookies collection of the response, or to the URL if you are using cookieless authentication.
SetAuthCookie (String, Boolean, String) Creates an authentication ticket for the supplied user name and adds it to the cookies collection of the response, using the supplied cookie path, or using the URL if you are using cookieless authentication.

The translation here will not be mentioned. It will naturally know what the description is. Many times, such as the description, it is difficult to explain the specific use of a method, however, I learned how to use it several times.

For more information, see the Reference url provided above. I will only describe the usage here.

 

 Let's take a look at the description of FormsAuthentication. RedirectFromLoginPage.

Reference: http://msdn.microsoft.com/zh-cn/library/system.web.security.formsauthentication.redirectfromloginpage (v = VS.80). aspx

Redirects authenticated users back to the original requested URL or default URL.

Name Description
FormsAuthentication. RedirectFromLoginPage (String, Boolean) Redirects authenticated users back to the original requested URL or default URL.
FormsAuthentication. RedirectFromLoginPage (String, Boolean, String) Use Forms to authenticate the specified Cookie Path and redirect authenticated users back to the original requested URL or default URL.

I don't want to explain it. The following is an example. I am also afraid of readers. What I want is the ready-made code, isn't it? Actually, this is what I think.

 

1. If you do not use the built-in logon Control for login verification, the page will always need to be verified because there is no value in the page Cookie. The user's login ID value must be paid to the AuthCookie after the user login authentication is successful. The following is the login authentication and the login user information must be added to the AuthCookie.

Key code:

FormsAuthentication. SetAuthCookie (userName, false );

    FormsAuthentication.RedirectFromLoginPage(userName, false);
Protected void btnLogin_Click (object sender, EventArgs e) {string userName = txtUserName. text. trim (); string password = txtPassword. text. trim (); string validateCode = txtValidateCode. text. trim (); BizResult <bool> bizResult = UserManager. userLogin (userName, password, validateCode); if (bizResult! = Null & bizResult. isSuccess) {FormsAuthentication. setAuthCookie (userName, false); FormsAuthentication. redirectFromLoginPage (userName, false); string message = "successfully logged on to the system"; // # if! DEBUG BaseConfigManager baseManager = new BaseConfigManager (); baseManager. addBillingOperationLog (3, message, 1); // # endif} else {ClientScript. registerStartupScript (typeof (_ Default), "NO_SUCH_EMPLOYEE", "<script> alert ('" + bizResult. returnString + "') </script> ");}}

 

2. Get the current user (this is the key to use. I don't know how to use it by inserting things into the AuthCookie. What should I do ?)

Key code:

    HttpCookie cookie = HttpContext. Current. Request. Cookies. Get (FormsAuthentication. FormsCookieName );

     FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);      string userName = ticket.Name;
/// <Summary> /// obtain the current user /// </summary> /// <returns> </returns> public static UserInfo GetCurrentUser () {HttpCookie cookie = HttpContext. current. request. cookies. get (FormsAuthentication. formsCookieName); if (cookie = null | string. isNullOrEmpty (cookie. value) return null; FormsAuthenticationTicket ticket = FormsAuthentication. decrypt (cookie. value); string userName = ticket. name; if (! String. isNullOrEmpty (userName) {if (userName = CmfuConfig. instance. deleetting. powerUserName) {UserInfo user = new UserInfo (); user. id =-1; user. userName = CmfuConfig. instance. deleetting. powerUserName; user. passWord = CmfuConfig. instance. deleetting. powerUserPwd; user. pageRoleId = CmfuConfig. instance. deleetting. ADMINPAGEROLE; user. appRoleId = CmfuConfig. instance. deleetting. ADMINAPPROLE; user. app RoleName = "Super administrator"; user. pageRoleName = "Super administrator"; user. status = 1; return user;} else {BizResult <UserInfo> returnObj = UserManager. getUserByUserName (userName); if (returnObj! = Null & returnObj. IsSuccess) return returnObj. ReturnObject ;}} return null ;}

 

3. The current Login User exits

Protected void lbtnSignOut_Click (object sender, EventArgs e) {FormsAuthentication. SignOut (); // exit the current logon. Response. Redirect ("/Login. aspx"); // page redirection}

 

Summary:

FormsAuthentication. SetAuthCookie: Create an authentication ticket and attach it to the Cookie
The SetAuthCookie and RedirectFromLoginPage methods in FormsAuthentication record user login information (TAG) to the Cookie.
In Forms authentication, HttpContext. Current. User. Identity. IsAuthenticated depends on the information in this Cookie to determine whether the User logs in.
FormsAuthentication. SignOut is used to clear this Cookie flag


MVC4 Forms authentication, deployed on Hyper-v FormsAuthenticationSetAuthCookie is invalid

I have also encountered this problem. This is a bug in IE10 or asp. A Bug in net4 that changes the http header in IE10, resulting in asp. net4 considers that the client does not enable the cookie, which may cause verification failure.
A simple solution is to add a browser definition file in the root directory of the website)
The procedure is as follows:
1. Add a "App_Browsers" folder
2. Add a file with the suffix "*. browser", such as IE10.browser.
3. Add the following file:
<Browsers>
<Browser refID = "Default">
<Capabilities> <! -- To avoid wrong detections of e.g. IE10 -->
<Capability name = "cookies" value = "true"/>
<Capability name = "ecmascriptversion" value = "3.0" type = "apiname" text = "apiname"/>
</Capabilities>
</Browser>
</Browsers>

Asp net uses formsauthenticationsetauthcookie () for security

This verification mechanism is safe, but it is troublesome and inflexible, and less useful for commercial projects.
 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.