ASP (c): Use Digest authentication for security Validation (Digest authentication)

Source: Internet
Author: User

In the previous article, we mainly discussed the use of HTTP Basic authentication method, because the way HTTP Basic authentication determines that it has a large security problem, so next look at another way to verify: Digest authentication, that is, Digest authentication.

Series Articles List

ASP (i): Using the first approach, get and post data
ASP (b): Security authentication using HTTP Basic authentication
ASP (c): Use Digest authentication for security Validation (Digest authentication)

Summary authentication principle

In the Basic authentication way, the main security problem comes from the clear-text transmission of the user information, but in the digest authentication, mainly through some means to avoid this problem, greatly increased the security.

The validation principle flowchart for summary validation.

Let's take a look at this part of the verification process:

    1. Client request/api/employees;
    2. The server returns a 401 unverified state, and the returned information contains the value of the authentication method Digest,realm, QOP (Quality ofprotection) is only set to Auth,nonce as a string of random values, In the following request will always be used, when the survival period after the server will be refreshed to generate a new nonce value;
    3. After the client accepts that the request returns, the Username:realm:password is hashed, assuming that the value after the operation is HA1. The requested path/api/employees is also hashed, assuming that the value after the operation is HA2. The HA1:nonce:nc:cnonce:qop:HA2 is then hashed, and the resulting value is placed in the response. The cnonce here is the nonce value generated by the client, and the NC is used for statistics, assuming that at the beginning is 00000001, the next request becomes 00000002, not necessarily adding 1 each time, but the NC value in the subsequent request is definitely greater than the NC value in the previous request.
    4. When the server receives the request, it verifies that the nonce expires, and if it expires, returns 401, which is the state of the second step. If there is no expiration, then the NC value is compared, if it is smaller than the previous NC value or the previous NC value is not stored at all, then the 401 state will also be returned directly. If the previous validation is passed, then the server will also follow the steps in step 3 to calculate the final hash value of the calculation of the hash value and the client comparison, and then compare the hash value submitted by the client and the server to calculate the hash to compare, do not match return 401, Match gets the requested data and returns the status 200.

Abstract verification is mainly through the above hash comparison steps to avoid the basic verification of security issues.

It is important to note that if IIS is required to support digest validation, the features of the IIS Digest validation need to be ticked.

Implementation of summary validation

After understanding the principle of digest validation, you only need to implement it in code.

The method of judging if the nonce is out of date.

1          Public Static BOOLIsValid (stringNoncestringnoncecount)2         {3tuple<int, datetime> cachednonce =NULL;4Nonces. TryGetValue (Nonce, outcachednonce);5 6             if(Cachednonce! =NULL)//nonce is found7             {8                 //nonce count is greater than the one in record9                 if(Int32.Parse (Noncecount) >cachednonce.item1)Ten                 { One                     //nonce have not expired yet A                     if(Cachednonce.item2 >DateTime.Now) -                     { -                         //update the dictionary to reflect the nonce count just received in this request theNonces[nonce] =Newtuple<int, datetime>(Int32.Parse (noncecount), - Cachednonc E.ITEM2); -  -                         //every thing looks ok-server nonce is fresh and nonce count seems to be +                         //incremented. Does not a look like replay. -                         return true; +                     } A                 } at             } -  -             return false; -}
code to determine if a nonce is out of date

The following is the core approach to summary validation implementation

1 namespacedigestauthentication2 {3      Public classAuthenticationhandler:delegatinghandler4     {5         protected Async OverrideTaskSendAsync (httprequestmessage request, CancellationToken CancellationToken)6         {7             Try8             {9                 varheaders =request. Headers;Ten                 if(Headers. Authorization! =NULL) One                 { AHeader Header =NewHeader (Request. Headers.Authorization.Parameter, -  Request. Method.method); -  the                     if(Nonce.isvalid (header). Nonce, header. Nouncecounter)) -                     { -                         //Just Assuming password is same as username for the purpose of illustration -                         stringPassword =header. UserName; +  -                         stringHA1 = String.Format ("{0}:{1}:{2}", header. UserName, header. Realm, +  Password). Tomd5hash (); A  at                         stringHA2 = String.Format ("{0}:{1}", header. Method, header. Uri). Tomd5hash (); -  -                         stringComputedresponse =String -. Format ("{0}:{1}:{2}:{3}:{4}:{5}", - HA1, header. Nonce, header. Nouncecounter, -Header. Cnonce,"Auth", HA2). Tomd5hash (); in  -                         if(String.compareordinal (header). Response, computedresponse) = =0) to                         { +                             //Digest computed matches the value sent by client in the response field. -                             //Looks like an authentic client! Create a principal. the                             varClaims =NewList<claim> *                             { $                                             NewClaim (Claimtypes.name, header. UserName),Panax Notoginseng                                             NewClaim (Claimtypes.authenticationmethod, Authenticationmethods.password) -                             }; the  +                             varPrincipal =NewClaimsPrincipal (New[] {NewClaimsidentity (Claims,"Digest") }); A  theThread.CurrentPrincipal =principal; +  -                             if(HttpContext.Current! =NULL) $HttpContext.Current.User =principal; $                         } -                     } -                 } the  -                 varResponse =await Base. SendAsync (Request, cancellationtoken);Wuyi  the                 if(Response. StatusCode = =httpstatuscode.unauthorized) -                 { WuResponse. HEADERS.WWWAUTHENTICATE.ADD (NewAuthenticationheadervalue ("Digest", - Header.unauthorizedresponseheader . ToString ())); About                 } $  -                 returnresponse; -             } -             Catch(Exception) A             { +                 varResponse =request. Createresponse (httpstatuscode.unauthorized); theResponse. HEADERS.WWWAUTHENTICATE.ADD (NewAuthenticationheadervalue ("Digest", - Header.unauthorizedresponsehead Er. ToString ())); $  the                 returnresponse; the             } the         } the     } -  in}
the core method of summary verification implementation

Once the implementation is complete, use digest validation to simply add the [authorize] property tag to the corresponding method.

Advantages and disadvantages of summary validation

Summary validation is a good solution to the security concerns of using Basic authentication.

But there is always no absolute security, when users use the dictionary for the poor lifting crack, there will be some cracked hidden trouble.

SOURCE download

How can I not find a place to upload files in the editor? I uploaded to the Baidu network disk.

Source code Download

Reference page:hTTP://QINgQINgQuege.CNbLogs.Com/P/5933752.hTmL

ASP (c): Use Digest authentication for security Validation (Digest authentication)

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.