When you do a website, you will use the function of user login. For sensitive resources, we only want authorized users to be able to access it, which makes it necessary for the user to authenticate. For beginners, usually the user login information stored in the session, the author in the first contact with the asp.net is the time to do so. When I present the user information in the session, it is often encountered that the sessions are lost, resulting in the user's inability to access the authorized resources normally, and the security of maintaining the user's login status. In ASP.net, we have a better solution, which is to authorize users by forms authentication, which makes it easy to maintain the user's login status (if the user wants it), convenient user authorization configuration, enhanced security, and more. Nonsense no longer say more, below we do a simple use
Before doing the example, we first define the following user class, the class name is Sampleuser, and the code is as follows:
public partial class sampleuser { string username; public string username { get { return username; } set { username = value; } } string userpwd; public string UserPWD { get { return userpwd; } set { userpwd = value; } } public override
bool equals (object obj) { Sampleuser other = obj as sampleuser; if (other == null | | other. Username != this. UserName) return false; return true; } } public partial class sampleuser { public static listuserlist = new List{ new sampleuser () { username = ", userpwd = " "123"}, new Sampleuser () { UserName = ", userpwd = " "123" }, new sampleuser () { UserName = " userpwd" = "123" }, New sampleuser () { UserName = ", userpwd = " }, "123" }; public static SampleUser
GetUser (string username) { return userlist.find (u=>u.username == username); } }
In class Sampleuser, the username and userpwd two fields are defined to store the user's logon name and password information, respectively. In another part of the Sampleuser class, we provide a static class table of users that replaces the user information stored in the database and provides a method getuser for obtaining user information.
In this example, we demonstrate that the user must be logged in to access the site's resources, and if they are not logged in, navigate the user to the Login.aspx page.
The first step is to add configuration information to the web.config that the Web site uses Forms authentication, specify the login page and the jump page after the default login succeeds, and then specify to deny access to the Logged-in user, as follows:
<authentication mode= "Forms" > <forms loginurl= "~/login.aspx" defaulturl= "~/default.aspx
"/>
</authentication>
<authorization>
<deny users= "?" />
</authorization>
After this step, we open the Default.aspx page again, in the absence of login, the page will be navigated to the Login.aspx page, our first step of the goal has been achieved.
The second step is to complete the Login.aspx page logic. Add two TextBox controls to the page to enter a username and password, add a CheckBox control to choose whether to remain logged on, and add a button control to respond to user logon actions. The corresponding code is as follows:
<fieldset> <legend> User Login </legend> <div> User name: <asp:textbox id= "Txtuserid" runat= "Server" width= " " /><br /><br /> secret code:< Asp:textbox id= "Txtuserpwd" runat= "Server" textmode= "Password" width= " /><" br /><br /> <asp:checkbox id= "CbSaveUserName" runat= "Server" checked= "true" text= "Stay logged in" /> </div>< br /> <asp:literal id= "Ltmessage" text= " runat=" "Server"
visible= "false" /> <br /> <p> <asp:button id= "Btnlogin" text= "Landing" runat= "server" onclick= "Btnlogin_click " /> </p> </fieldset>
Next complete the background code, add a login button to the background processing method: The user name and password authentication, if the validation pass, then create an authentication ticket for the user name and add it to the response cookie. The code is as follows:
Protected void btnlogin_click (object sender, eventargs e) {
string userid = this.txtuserid.text.trim ();
string userpwd = this.txtuserpwd.text.trim ();
sampleuser userex = sampleuser.getuser (UserID);
if (userex == null) { ltMessage.Text = "user does not exist!"
";
ltMessage.Visible = true;
return; &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP} if (userex.userpwd != USERPWD) { ltmessage.text = username or password is wrong, please re-enter!
"; ltmessage.visible = true;
return; &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP} //Add the ticket and navigates the user to the default page formsauthentication.redirectfromloginpage (userex.username, this.cbsaveusername.checked)
; }
By completing this step, we have completed the function of simple froms verification. Run the program and you'll find that there's a problem here!!!
Did you find it? When we were navigated to login.aspx, the style of this page was lost! This is because we have access to the resources of the entire site, if not logged in, users can not only access the. aspx page, even CSS files, JS files are inaccessible. Obviously, this is not what we want, because these resources are not sensitive resources. In general, we only want to restrict the access to the files in some folders, not the entire site, for example, we allow access to only the pages under the user folder, because this folder has private information about the users, and this information is sensitive. How can this be achieved?
To complete the demo catalog validation, we add a user folder to the project and add userinfo.aspx, userlogin.aspx two pages. Userinfo.aspx is used to display user information, its business logic we are not our concern, Userlogin.aspx page is used to let the user log in, the code is almost identical to the Login.aspx page.
First step: Modify the Web.config file to allow anonymous users access to system resources.
<authorization>
<allow users= "?" />
</authorization>
Step two: Add a Web.config file under the user folder, modify the code, and deny anonymous users access to resources under the folder.
<authorization>
<deny users= "?" />
</authorization>
After these two steps, when we visit userinfo.aspx, if there is no landing, will be navigated to the ~/user/userlogin.aspx page, when landing, will be navigated to the ~/user/userinfo.aspx page. At this time, our landing page style is not lost, which means that our configuration file is working.
Next, we would like to display the user name and password of the logged on user in the Userinfo.aspx page (this is entirely to demonstrate how to obtain the login data to do so, usually the user's password is not displayed). After landing, the user's ticket information is encrypted stored in the cookie, this ticket, there are logged in the user's name information, we get the ticket in the user name, you can get the full user information.
To display the user information, we placed two label controls on the page with the following code:
Then, in the page's Load method, we get and present the user information:
if (this. Context.User!= null && this. Context.User.Identity!= null && this. Context.User.Identity.IsAuthenticated)
{
Sampleuser User = Sampleuser.getuser (this. Context.User.Identity.Name);
if (user!= null)
{
this.lblUserName.Text = user. UserName;
This.lblUserPWD.Text = user. Userpwd;
}
}
Run our code again, and when the user logs in (if the login is maintained, even if the browser is turned off and reopened), we can get the name of the logged-on user to get the user's object.
If you want to exit the login, we just need to delete the ticket information stored in the cookie, which has been done for us, and the code is simple:
FormsAuthentication.SignOut (); Exit Login
In this article, role validation is not involved because it is not flexible enough to specify a role in the configuration file, and if the role can be maintained in the program, then our designation here is in no way. Interested friends can learn by themselves and are not complicated. At the end of this article, attach detailed forms validation in Web.config configuration instructions:
<forms
name= "name"
loginurl= "url"
defaulturl= "url"
protection= "[all| none| encryption| Validation] "
timeout=" [MM] "
path=" path "
requiressl=" [True|false] "
slidingexpiration=" [True|fal SE] ">
enablecrossappredirects=" [True|false] "
cookieless=" [useuri| usecookie| Autodetect| UseDeviceProfile] "
domain=" domain name "
ticketcompatibilitymode=" [framework20| FRAMEWORK40] ">
<credentials>...</credentials>
</forms>
Name: Specifies the HTTP Cookie to use for authentication. If you are running multiple applications on a single server and each application requires a unique cookie, you must configure the cookie name in the Web.config file for each application. The default value is ". Aspxauth ".
Loginurl: Specifies the URL that will be redirected to the login if no valid authentication Cookie is found. The default value is Login.aspx.
Defaulturl: Defines the default URL that is used for redirection after authentication. The default value is "default.aspx".
Protection: Specifies the type of encryption (if any) that the Cookie uses. The default value is all.
Timeout: Specifies the elapsed time (in integer minutes) before the Cookie expires. If the SlidingExpiration property is true, the Timeout property is a sliding value that expires after the specified time (in minutes) after the last request is received. To prevent performance from being compromised and to avoid multiple browser warnings to users that turn on cookie warnings, the cookie is updated when the specified time elapses. This can result in a loss of accuracy. The default value is "30" (30 minutes).
Path: Specifies the path for the Cookie emitted by the application. The default value is a slash (/), because most browsers are case-sensitive and the browser will not send cookies back if the path case does not match.
requireSSL: Specifies whether an SSL connection is required to transmit the authentication Cookie. The default value is False.
SlidingExpiration: Specifies whether the adjustable expiration time is enabled. Adjustable expiration Resets the current authentication time for a Cookie to expire when each request is received during a single session. The default value is True.
enableCrossAppRedirects: Indicates whether the authenticated user is redirected to a URL in another WEB application. The default value is False.
Cookieless: Defines whether to use cookies and the behavior of cookies. The default value is UseDeviceProfile.
Domain: Specifies the optional domain that is set in the outgoing Forms authentication Cookie. This setting has a higher precedence than the domain used in the httpcookies element. The default value is an empty string ("").
Ticketcompatibilitymode: Specifies whether Coordinated Universal Time (UTC) or local time is used for the ticket expiration date in Forms authentication. The default value is Framework20.
Child element Credentials: Allows you to choose to define name and password credentials in the configuration file. You can also implement a custom password schema to use external sources such as databases to control validation.