In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly shows you the "sample analysis of Forms authentication in asp.net", which is easy to understand and well-organized. I hope it can help you solve your doubts. Let me lead you to study and study the "sample analysis of Forms authentication in asp.net".
When making a website, the function of user login will be used. For some sensitive resources, we only want authorized users to have access, which requires user authentication. For beginners, user login information is usually stored in Session, which is what I did when I first came into contact with asp.net. When I store user information in Session, I often encounter the security problem when users cannot access authorized resources properly due to the loss of Session. In fact, in asp.net, we have a better solution, that is, to authorize users through Forms authentication. This method can easily maintain the login status of users (if users want to). Convenient user authorization configuration, enhanced security and other benefits.
Before making an example, let's define the following user class, named SampleUser, and the code is as follows:
Public partial class SampleUser {string username; public string UserName {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 List userList = new List {new SampleUser () {UserName = "01", UserPWD = "123"}, new SampleUser () {UserName = "02", UserPWD = "123"}, new SampleUser () {UserName = "03", UserPWD = "123"}, new SampleUser () {UserName = "04", UserPWD = "123"},} Public static SampleUser GetUser (string userName) {return userList.Find (u = > u.UserName = = userName);}}
In the class SampleUser, two fields, UserName and UserPWD, are defined to store the user's login name and password information, respectively. In another part of the SampleUser class, we provide a static class table for the user instead of the user information stored in the database and a method GetUser to get the user information.
In this example, we demonstrate that the user must log in to access the resources of the site, and if not, navigate the user to the login.aspx page.
The first step is to add configuration information to web.config, indicating that the website should use Forms authentication, and specify the login page and the jump page after the default login is successful, and then specify to deny access to unlogged-in users, as follows:
After completing this step, we open the Default.aspx page, without login, the page will be navigated to the Login.aspx page, our first step has been achieved.
The second step is to complete the page logic of Login.aspx. Add two TextBox controls to the page to enter the user name and password; add a CheckBox control to choose whether to keep the login state; and add a Button control to respond to the user's login operation. The corresponding code is as follows:
User login user name: password:
Next, finish the background code and add the background processing method of the login button: verify the user name and password, and if the verification passes, create an authentication ticket for the user name and add it to the Cookie of the response. 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;} if (userEx.UserPWD! = userPWD) {ltMessage.Text = "wrong username or password, please enter it again!" ; ltMessage.Visible = true; return;} / / add the ticket and navigate the user to the default page FormsAuthentication.RedirectFromLoginPage (userEx.UserName, this.cbSaveUserName.Checked);}
After completing this step, we have completed the function of simple Froms validation. Run the program, you will find that there is a problem!
Did you find out? When we were navigated to login.aspx, the style of this page was lost! This is because we have restricted access to the resources of the entire website. If we do not log in, users will not be able to access not only .aspx pages, but even css files and js files. Obviously, this is not what we want, because these resources are not sensitive resources. In general, we only want to verify access restrictions on files in some folders, not the entire site. For example, we allow access restrictions only on pages under the User folder, because this folder contains the user's private information, which is sensitive. How can this be achieved?
In order to complete the demonstration subdirectory verification, we add a User folder to the project and add two pages, UserInfo.aspx and UserLogin.aspx. UserInfo.aspx is used to display user information, its business logic we do not care about, UserLogin.aspx page is used to let users log in, the code is almost exactly the same as Login.aspx page.
Step 1: modify the Web.config file to allow anonymous users to access system resources.
Step 2: add a Web.config file under the User folder, modify the code, and deny anonymous users access to the resources under the folder.
After completing these two steps, when we visit UserInfo.aspx, if we do not log in, we will be navigated to the ~ / User/UserLogin.aspx page, and when we log in, we will be navigated to the ~ / User/UserInfo.aspx page. At this time, our login page style is not lost, which shows that our configuration file is working.
Next, we want to display the user name and password of the logged-in user on the UserInfo.aspx page (this is done entirely to demonstrate how to get the logged-in user data, which is usually not shown). After logging in, the user's ticket information is encrypted and saved in Cookie. In this ticket, there is the name information of the logged-in user. We can obtain the complete user information by obtaining the user name in the ticket.
To display user information, we put two Label controls on the page with the following code:
User name:
Secret code:
Then, in the Load method of the page, we get and display 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 (even if the browser is closed and reopened if the login status is maintained), we can get the Name of the logged-in user and get the user's object.
To log out, we only need to delete the ticket information saved in Cookie. The Forms verification of this function has been done for us, and the code is very simple:
FormsAuthentication.SignOut (); / / log out
In this article, role verification is not covered, because the method of specifying roles in the configuration file is not flexible enough, and if the roles can be maintained in the program, then our assignment here is non-existent. Interested friends can learn by themselves, which is not complicated. At the end of this article, a detailed configuration description of Forms authentication in Web.config is attached:
EnableCrossAppRedirects= "[true | false]" cookieless= "[UseUri | UseCookie | AutoDetect | UseDeviceProfile]" domain= "domain name" ticketCompatibilityMode= "[Framework20 | Framework40]" >.
Name: specifies the HTTP Cookie to be used 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 to which the request is redirected for login if no valid authentication Cookie is found. The default is login.aspx.
DefaultUrl: defines the default URL for redirection after authentication. The default is "default.aspx".
Protection: specifies the type of encryption that Cookie uses, if any. The default 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 and expires after the specified time (in minutes) after the previous request was received. To prevent performance from being compromised and to avoid issuing multiple browser warnings to users with Cookie warnings on, Cookie is updated when most of the specified time has elapsed. This can lead to impaired accuracy. The default value is 30 (30 minutes).
Path: specifies the path for the Cookie emitted by the application. The default is a slash (/), because most browsers are case-sensitive, and if the path does not match, the browser will not send back Cookie.
RequireSSL: specifies whether an SSL connection is required to transmit the authentication Cookie. The default is False.
SlidingExpiration: specifies whether the adjustable expiration time is enabled. Adjustable expiration resets the current authentication time of Cookie to expire when each request is received during a single session. The default is True.
EnableCrossAppRedirects: indicates whether authenticated users are redirected to URL in other Web applications. The default is False.
Cookieless: defines whether to use Cookie and the behavior of Cookie. The default value is UseDeviceProfile.
Domain: specifies the optional domain set in the outgoing Forms authentication Cookie. This setting takes precedence over the domain used in the httpCookies element. The default is an empty string (").
TicketCompatibilityMode: specifies whether coordinated Universal time (UTC) or local time is used for ticket expiration dates in Forms authentication. The default 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 control authentication using an external source, such as a database.
The above is all the content of the article "sample Analysis of Forms Authentication in asp.net". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.