[ASP. net mvc] implement Basic authentication using custom AuthenticationFilter

Source: Internet
Author: User
Tags http authentication

In many cases, the target Action method must be executed in a security context. The so-called security context mainly refers to that the current requester is an authorized user. The essence of authorization is to allow the user to do what he can do within the scope of his permission. The premise of authorization is that the requester is an authenticated user. Chanllenge-Response is a common form used for user authentication. The authenticated Party sends a question to the authenticated party to provide the user creden, for authentication, the authenticated party provides the corresponding creden。 to respond to the question. AuthenticationFilter, which aims to implement identity authentication before the execution of the target Action method, also supports this authentication method.

I. IAuthenticationFilter Interface

All AuthenticationFilter types implement the IAuthenticationFilter interface, which is defined in the namespace "System. web. mvc. filters (the other four filter interfaces are defined in System. web. mvc ). As shown in the following code snippet, The OnAuthentication and OnAuthenticationChallenge methods are defined in this interface. The former is used to authenticate requests, and the latter is responsible for sending the corresponding authentication question to the requester.

     
      
       
        
     

Both methods defined in the IAuthenticationFilter interface use a context object as its unique parameter. The parameter type of the onauthententication method is AuthenticationContext, as shown in the following code snippet, which is a subclass of ControllerContext. The ActionDescriptor of AuthenticationContext returns the ActionDescriptor object used to describe the target Action method. With the Principal attribute, we can obtain or set the Principal object representing the current user. If the Result attribute of AuthenticationContext is set during OnAuthentication method execution, the provided ActionResult is directly used to respond to the current request.

          
           
            
             
              
               
                
                 
              

The parameter type of the OnAuthenticationChallenge method is AuthenticationChallengeContext. As shown in the following code snippet, it is still a subclass of ControllerContext. It also has an ActionDescriptor attribute used to describe the target Action method. The ActionResult object represented by its Result attribute is used to respond to the current request.

                   
                    
                     
                      
                       
                        
                         
                          
                           
                            
                         
Ii. Execution Process of AuthenticationFilter

We know that identity authentication is always the first step in request processing, because security can be guaranteed only by determining the real identity of the requester, so AuthenticationFilter is the first type of filter to be executed. The execution of all filters is driven by ActionInvoker. By default, ASP. net mvc adopts ActionInvoker as an AsyncControllerActionInvoker object, which is derived from ControllerActionInvoker. The execution of ControllerActionInvoker for AuthenticationFilter is reflected in the following two methods (InvokeAuthenticationFilters and InvokeAuthenticationFiltersChallenge.

                              
                               
                                
                                 
                                  
                               If multiple authenticationfilters are applied to the target Action method at the same time, ControllerActionInvoker sorts them according to the Order/Scope attribute of the Filter. Then, ControllerActionInvoker creates an AuthenticationContext object based on the current ControllerContext, The ActionDescriptor object that describes the target Action method, and the original Principal (corresponding to the User attribute of the current HttpContext, as a parameter, the OnAuthentication object of each AuthenticationFilter object is called for authentication.

After the target Action method is executed, we can see that the final execution result will be encapsulated into an ActionResult object through "View presentation" in Chapter 11th of this book. ControllerActionInvoker creates an AuthenticationChallengeContext object using the current ControllerContext, ActionDescriptor object that describes the target Action method, and the ActionResult, and calls the OnAuthenticationChallenge method of each AuthenticationFilter as parameters. The ActionResult object returned by the Result attribute of the AuthenticationChallengeContext object will be used to respond to the request.

The figure on the right shows the execution process of the entire "AuthenticationFilter chain". However, if the OnAuthenticatio method of an AuthenticationFilter object is executed, the Result attribute of the AuthenticationContext object as the parameter is set accordingly, the execution of the entire "AuthenticationFilter chain" will be immediately aborted, and the specified ActionResult object will be used to respond to the current request. If the Principal attribute of the AuthenticationContext object is set during execution, the attribute value will be used as the Principal of the current HttpContext and the current thread.

Iii. Example: Implement Basic authentication through custom AuthenticationFilter

In the Application Programming Interface of ASP. net mvc, we cannot find the implementer of the IAuthenticationFilter interface. To enable you. net mvc 5 introduces a more profound understanding of the filter, we will use an example to demonstrate how to use the custom AuthenticationFilter for Basic authentication. However, before that, it is necessary to have a Basic understanding of the Basic authentication method. Basic and Digest are two typical HTTP authentication schemes. For the former, although the authentication credential (username + password) provided by the client is only Base64 encoded but not encrypted, We Can Use HTTPS transmission to solve the confidentiality problem, therefore, Basic authentication is also a good authentication solution. The figure on the left shows the Basic authentication process. It can be seen that this is also a typical authentication solution using the "Question-Answer" mode. The entire process includes the following two Basic steps.

  • The client sends an HTTP request to the server. The server returns a 401, Unauthorized response. The response has a "WWW-Authenticate" header indicating that the Basic authentication scheme is used. Basic authentication is performed in a context defined by "Realm (Realm)". This header can also be used for authentication. The WWW-Authenticate header value shown in the left figure is: basic realm = "localhost ".
  • · The client sends a request to the server with a user name/password-based authentication credential. The authentication credential is in the format of "{UserName }:{ Password}" and Base64 encoding (encoding is not intended to protect the provided Password ). Such an encoded authentication credential is stored in the Request Header Authorization. The corresponding authentication scheme type (Basic) still needs to be specified in the header. The Authorization header value shown in the left figure is: basic YcdfaYsss =. After receiving the request, the server extracts the credential from the Authorization header and decodes it. Finally, the server authenticates the credential using the extracted user name and password. After successful authentication, the request will be processed normally and a normal response will be returned.

Before officially introducing the Implementation of the Basic Authentication AuthenticationFilter, let's take a look at the effect of using this custom AuthenticationFilter. In an ASP. net mvc application, we define the next HomeController. The default Action method Index will output the "current user name" in three forms ". The AuthenticateAttribute attribute applied on the HomeController type is our custom AuthenticationFilter.

                                    
                                     
                                      
                                       
                                        
                                         
                                          
                                           
                                            
                                         

Because the browser supports Basic authentication by default, the logon dialog box shown in is automatically displayed after the program is run, after you enter the correct user name and password (the user name and password are directly maintained on AuthenticateAttribute), the current user name will be displayed in the browser.

The AuthenticateAttribute used for Basic authentication is defined as follows. For simplicity, we save the username and password used by the account in a static field. Specific authentication implementation in the OnAuthentication method implemented, we call IsAuthenticated in this method to determine whether the authentication is successful, and obtain the Principal object representing the requesting user if the authentication is successful, however, assign a value to the Principal attribute of the AuthenticationContext object as the parameter. For Unauthenticated requests, we will call another method ProcessUnauthenticatedRequest to process them.

                                              
                                               
                                                
                                                 
                                                  
                                                   
                                                    
                                                     
                                                      
                                                       
                                                        
                                                         
                                                          
                                                           
                                                            
                                                             
                                                              
                                                               
                                                                
                                                                 
                                                                  
                                                                   
                                                                    
                                                                     
                                                                      
                                                                       
                                                                        
                                                                         
                                                                          
                                                                           
                                                                            
                                                                             
                                                                              
                                                                               
                                                                                
                                                                                 
                                                                                  
                                                                                   
                                                                                    
                                                                                     
                                                                                      
                                                                                       
                                                                                        
                                                                                         
                                                                                          
                                                                                           
                                                                                            
                                                                                             
                                                                                              
                                                                                               
                                                                                                
                                                                                                 
                                                                                                  
                                                                                                   
                                                                                                    
                                                                                                     
                                                                                                      
                                                                                                       
                                                                                                        
                                                                                                         
                                                                                                          
                                                                                                           
                                                                                                            
                                                                                                             
                                                                                                              
                                                                                                               
                                                                                                                
                                                                                                                 
                                                                                                                  
                                                                                                                   
                                                                                                                    
                                                                                                                     
                                                                                                                      
                                                                                                                       
                                                                                                                        
                                                                                                                         
                                                                                                                          
                                                                                                                           
                                                                                                                            
                                                                                                                             
                                                                                                                              
                                                                                                                               
                                                                                                                                
                                                                                                                                 
                                                                                                                              

In the IsAuthenticated method that implements authentication on the request, we will try to extract the Security credential from the Authorization header of the request, and parse the username and password according to the Basic credential format. Only when the username and password match, we believe that the request passes authentication and create a GenericPrincipal object based on the parsed username as the output parameter user value. If the request is authenticated (it can be an anonymous request, or the provided user name does not match the password), The ProcessUnauthenticatedRequest method is called. In this case, it sets the response WWW-Authenticate header and creates an HttpUnauthorizedResult object as the Result attribute of the AuthenticationContext object, then the client will eventually receive a response in the "401, Unauthorized" status.

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.