ASP. NET form authentication and Role authorization, asp.net form

Source: Internet
Author: User

ASP. NET form authentication and Role authorization, asp.net form

Refer:

Process Diagram for processing requests in http://hi.baidu.com/iykqqlpugocfnqe/item/e132329bdea22acbb6253105 ASP. NET

Http://www.cnblogs.com/yao/archive/2006/06/24/434783.html

Http://www.cnblogs.com/fish-li/archive/2012/04/15/2450571.html#_label3

This article mainly describes the implementation and logic process.

Authentication and authorization refer to access restriction management for a server resource.

For example, some files are not public and only accessible to administrators, which requires them to "Log on" first ". This is Authentication

Authorization occurs after authentication, and management personnel are classified. For example, some confidential documents of the company can only be viewed by the upper layer. This is authorization.

Microsoft has already encapsulated authentication and authorization for us. form authentication is one of them.

However, let's first think about how to implement it in the original age?

We all know that all web resources are accessed through http requests. Obviously, the first step is to intercept all undisclosed resources.

Step 2: Check whether they are "logged in ".

The so-called "login" is actually accomplished through a cookie.

If the request does not contain the specified cookie, it indicates that the request has not been logged on, and the access is blocked (and the logon page is displayed ).

After confirming the user password on the login page, the cookie will indicate that the user has logged on.

Step 3

After passing the authentication, we must check the user's identity (or role), such as the manager, supervisor, or common employee.

Further verify that the user has sufficient permissions (authorization) to access the resource.

Well, it's not that difficult. This is at least the case.

The preceding steps involve two important points:

1. What if I intercept a specific resource request?

2. cookie Security

Here is an example encapsulated by Microsoft. Generally, common projects are enough.

1. Add an authentication in web config

<system.web>      <authentication mode="Forms">    <forms loginUrl="~/login/Default.aspx" timeout="2880" defaultUrl="~/" />  </authentication></system.web>

Here, the mode is forms (I will only use this)

LoginUrl indicates the path of the login page, and timeout indicates the cookie validity period. I do not know the defaultUrl.

2. Create a login page, which is just done at will. You understand.

Protected void Page_Load (object sender, EventArgs e) {} protected void button#click (object sender, EventArgs e) // log on {// set a cookie, name and whether a persistent cookie is required, false indicates the timeout FormsAuthentication of base on web config. setAuthCookie ("keatkeat", false);} protected void Button2_Click (object sender, EventArgs e) // deregister {FormsAuthentication. signOut ();}

3. Set which file paths need to be intercepted for authentication

  <configuration>    <location path="securityFolder">      <system.web>        <authorization>          <deny users="?"/>        </authorization>      </system.web>    </location>  </configuration>

Path specifies the path, and all folders files under it are restricted.

There are multiple matching modes for elements in authorization

<Deny users = "? "> It is basically made by Dongdong of 3,

1. deny | allow (Forbidden or allowed)

2. users | roles | verbs (users, especially roles. I will teach you how to set one or more roles on one user, verbs is http method, GET POST, etc)

3 .? | *(? Represents anonymous, * represents all)

So the above explanation is-Prohibit anonymous users-(access is not allowed without logon)

After completing the above steps, you can basically implement a simple authentication and authorization mechanism (without the need to assign roles)

What if we want to be more advanced?

  <location path="securityFolder">     <system.web>      <authorization>             <allow roles="Admin,Boss"/>        <deny users="*"/>      </authorization>    </system.web>  </location>

Allow Admin or Boss roles to prohibit all users

Now we must add the user role to the user (because only the Name is provided to the user)

Class AuthenticateHttpModule: IHttpModule {public void Dispose () {} public void Init (HttpApplication context) {context. authenticateRequest + = new EventHandler (AuthenticateRequest);} private void AuthenticateRequest (object sender, EventArgs e) {HttpApplication app = (HttpApplication) sender; HttpContext ctx = app. context; // obtain the HttpContext object if (ctx. user! = Null) {if (ctx. request. isAuthenticated = true) // only authenticated users can perform role verification {string name = ctx. user. identity. name; FormsIdentity fi = (System. web. security. formsIdentity) ctx. user. identity; // FormsAuthenticationTicket ticket = fi. ticket; // get the authentication ticket // string userData = Ticket. userData; // restore role information from UserData string [] roles = "Admin, zz ". split (','); // convert the role data into a string array to obtain the relevant role information ctx. user = new GenericPrincipal (fi, roles); // now the current User has the role information }}}}

Here we need to write an HttpModule to complete the process (remember to add web config as well)

We can use new GenericPrincipal to add the role to the user.

Note: we run this module behind Microsoft, so we don't need to get anything from the cookie, just use context. User.

The above is probably the whole process.

Here is a custom example:

Public class AdministratorIdentity: IIdentity {public string AuthenticationType {get; set;} public string Name {get; set;} public bool IsAuthenticated {get; set ;}} public class Administrator: IPrincipal {public IIdentity Identity {get; set;} public string name {get; set;} // you can define the attribute public bool IsInRole (string role) at will) {if (role = "Admin") // all the verification methods you want can be {return true ;}return false ;}}
If (ctx. request. isAuthenticated = true) // only authenticated users can perform role verification {string name = ctx. user. identity. name; string type = ctx. user. identity. authenticationType; // custom ctx. user = new Administrator {name = "keatkeat", Identity = new AdministratorIdentity {AuthenticationType = ctx. user. identity. authenticationType, Name = "z", IsAuthenticated = true }}; // Method for adding roles in the original version // FormsIdentity fi = (System. web. security. formsIdentity) ctx. user. identity; // FormsAuthenticationTicket ticket = fi. ticket; // get the authentication ticket /// string userData = Ticket. userData; // restore role information from UserData // string [] roles = "Admin ". split (','); // convert the role data into a string array to obtain the relevant role information. // ctx. user = new GenericPrincipal (fi, roles); // The current User has the role information}

In this way, it is easy to use Ctx. User as Administrator ^

 

Here we also mention the security of cookie encryption.

First, if someone can get your cookie from your computer, then he will have all your permissions.

Second, if he hasn't intruded into your computer, can he create an encrypted cookie to simulate you?

The answer is no, because encryption works with the private key of the server when the cookie is created. (Like symmetric encryption)

Therefore, it is basically safe. Reference: http://blog.csdn.net/fancyf/article/details/348202

 

Next I will talk about some of my development experience.

Most of what we do today is single-page applications with only one login page and one home page. Other pages are virtual.

If you do the url rewrite by yourself, you must note that it is done only after the ResolveRequestCache (authentication and authorization module.

In the preceding section, if you want to implement it by yourself, you can use Microsoft's encryption method for cookie encryption. You can also inherit IPrincipal to implement your own User.

You can also register the HttpModule to intercept the AuthorizeRequest comparison path, and use SQL to obtain user positions for authorization verification.

If you use WebAPI, we recommend that you separate the two. The interception mentioned above is for access to page resources.

Webapis also have internal mechanisms to intercept authentication and authorization. Therefore, it is more appropriate to use the WebAPI mechanism to manage WebAPI resources.

WebAPI supports self host, but if we use IIS and it is greedy and convenient, we can also directly use the form authentication.

Therefore, the API request will still pass through the pipe of IIS to the API controller, and the User is still our context. User

If self host is used, you can use the above concepts. The cookie is replaced by the http header instead of the cookie.

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(2, loginName, DateTime.Now, DateTime.Now.AddDays(1), true, data);string cookieValue = FormsAuthentication.Encrypt(ticket);FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookieValue);

The principle of encryption and decryption is still correct.

 

Summary:

Simply put, authentication and authorization are nothing more than attaching an identity to the request and verifying the identity before the response.

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.