First of all, it should be declared that authentication and authorization are far more simple than what I will talk about below (otherwise, Jiri does not have to be immersed in it for many years ^_^ ). The following describes how to implement user authentication and authorization through the built-in functions in Asp.net, without having to judge whether the session is empty by writing on the page. If you already have this knowledge, skip it ......
User Authentication
. NET provides three user authentication methods: Windows, forms, and passport. The definitions can be seen in the authentication node in Web. config under the root directory of the website. Windows is the default authentication form, which is determined based on the access permission of the machine. Passport is a form of verification provided by Microsoft and is not commonly used. What we need to know is the forms form. Forms authentication provides authentication and authorization management in the form of ID and password.
Before formally using forms for verification, let's take a look at the process it runs:
We can see that we need to do a few things:
1. Configure web. config to enable Forms authentication
2. Configure authorization settings (which pages are accessible to unregistered users)
3. generate user tickets on the logon page to facilitate access to other pages
The following is a project example to demonstrate how to solve the problem.Source codeI will release it below. You can refer to the sourceCodeLook.First, let's take a look at the project to have an intuitive understanding:
Configure web. config.
The configuration method is as follows. Unverified users automatically jump to the page in loginurl to log on according to the configuration.
<Authentication mode ="Forms"> <Forms loginurl ="~ /Login. aspx"Defaulturl ="~ /Default. aspx"/> </Authentication>
Configure authorization settings
Add the following nodes under <system. Web> in Web. config: "?" "*" Indicates anonymous users, while "*" indicates all users. This means that all pages in the root directory are denied access by anonymous users. Of course, you can also enter the specified user ID in users, which is not commonly used. In addition, the order of "deny" and "allow" is to write "allow" before "deny". Otherwise, problems may occur. Remember this.
<Authorization> <deny users ="?"/> </Authorization>
Generate User Ticket
The following code is added to the logic code of the logon event (login. aspx:
// Create a ticket for the user and put it in the cookie or URL (depending on how you set the ticket storage method)Formsauthentication. setauthcookie (userid,True); Response. Redirect ("Info. aspx");
A few simple settings are used to complete user authentication. Is it easier to determine whether a user is logged on than you are on every page ?! Of course, the above authentication is simple authentication. If I want to implement a web page in the user folder that can only be accessed by login users, What can I do if all other users can access it? It is very simple and you do not need to write code. Change the configuration file. Change the authorization label of Web. config in the root directory to <allow users = "*"/>. Add a web. config file under the user file and modify the content as follows:
<Configuration> <etettings/> <connectionstrings/> <system. Web> <authorization> <deny users ="?"/> <! -- Reject anonymous user access --> </authorization> </system. Web> </configuration>
Now let's test the results. Therefore, by combining configuration files, you can construct a relatively complex user-authorized access mechanism. However, our users are not as simple as members and non-members. There are also categories for members, such as beginner and advanced. The users that these users can access are also different. At this time, this simple Login Without Logon judgment is useless, we need to introduce the concept of user role, that is, the user authorization we will talk about below.
User authorization
Here, the user authorization is mainly role-based authorization. As mentioned above, we have discussed the principle of user authentication, that is, to give the user an identity ticket during user logon, when a user logs on, the user will be able to know that the user has been authenticated through this ticket. Role authorization is to assume a string of role information in the ticket to the user, such as "Administrator ", then, when a request comes over, Asp.net will have an application_authenticaterequest event dedicated to user authentication and authorization. In this event, we only need to re-create the role expressed by this character to the user. It is a pity that. Net does not provide direct support for roles. Although the role characters are stored in cookies, we still need to write the role restoration process on the server side. Add the following code to the application_authenticaterequest method of Global. asax:
Protected Void Application_authenticaterequest ( Object Sender, eventargs e) {httpapplication APP = (httpapplication) sender; httpcontext context = app. context;// Obtain the httpcontext object of this HTTP Request If (Context. Request. isauthenticated) // A verified general user can perform role verification. {Formsidentity id = (formsidentity) Context. User. identity; // Current user ID Formsauthenticationticket ticket = ID. ticket; // Obtain the ID card ticket String [] Roles = ticket. userdata. Split (','); // Convert role data into a string array to obtain relevant role information Context. User = New System. Security. Principal. genericprincipal (ID, roles ); // Regenerate the user with role information }}
Because we need to add role information to the ticket, the method for adding a ticket in the above logon method is no longer applicable and changed to the following:
// Click the login button // Assume that the user has passed the database comparison. String Userid =" Qianlifeng "; String Pa =" 123 "; String Roles =" Administrator "; // Obtain user role data from other locations Formsauthenticationticket ticket = New Formsauthenticationticket (1, userid, datetime. Now, datetime. Now. addminutes (30 ), True , Roles ); // Create an identity authentication ticket object String Hashticket = formsauthentication. Encrypt (ticket ); // The encrypted serialization verification ticket is a string Httpcookie usercookie = New Httpcookie (formsauthentication. formscookiename, hashticket ); // Generate cookie Context. response. Cookies. Add (usercookie ); // Bill write cookie Response. Redirect (" Info. aspx ");
Finally, let's change the configuration file and set info. aspx to be accessible only by the administrator role. Add the following configuration under the <system. Web> label under Web. config in the root directory:
<Location Path ="Info. aspx"> <System. Web> <authorization> <allow roles ="Administrator"/> <Deny users ="*"/> </Authorization> </system. Web> </location>
Info. aspx is accessible only to members of the administrator role. Of course, if you want to implement the folder authorization settings, you just need to configure web. config in the folder similar to the above settings.
Similar Article Recommendation
In fact, there are already a lot of such articles in the garden. The reason why I want to write such an article is to deepen my understanding of this knowledge by writing blogs. The following is a good article on authentication and authorization. You can continue to look at it.
Impermanence, http://www.cnblogs.com/wuchang/archive/2004/07/26/27474.aspx
Yang Guo. Net under the bodhi tree,Http://www.cnblogs.com/yjmyzz/archive/2010/08/29/1812038.html
Source code download
Demo