Python API Simple Validation

Source: Internet
Author: User
Tags md5 encryption

Objective

Because of the needs of the CMDB, an API is required for data transmission, which is used to convey the information of the server that needs to be crawled to fetch the autoclient,autoclient and then transfer to the servers via API and save to the database. But to prevent malicious API access, you need to do a validation.

Imagine a

A string of random strings can be validated on both the client and the server, and it is only allowed to be accessed when the request is sent over with this string of authentication.

If you have learned the crawler, it is easy to find that this string of random strings in the browser is able to listen, a few more observations will always be found. And no matter how it is done, it will be noticed as long as it is exposed to the outer surface. At this point, you need to encrypt it.

Imagine two

Since the random string in the Web transport is clear state, then we try to convert it redact, the idea of conversion, if each request is a random string with a string of constantly changing values for MD5 encryption, at this time, the resulting validation string should also become dynamic ciphertext. What do dynamic strings do with MD5 encryption with a well-appointed string? Since it is dynamic, time stamping is the best choice.

At this time everything looks perfect, but, ignoring a point, whether it is not an encrypted string, HTTP requests can be heard at the time, so even if the encryption, even if you do not know how to encrypt, you can still directly take this string of strings directly to verify access. Embarrassed...

Imagine three

In fact, the above scenario two has done the dynamic, the idea as long as the change of a little immediately becomes feasible. In the case of HTTP requests, even in a fairly bad network environment, it does not take long to send, so it is possible to get stuck in time.

The timestamp of the client is that the server segment needs to be compared to the current timestamp only, and if the interval is less than 10 seconds, it is considered as normal access. You can do it.

The above design idea perfectly solves the dynamic problem, at this time inevitably has the question, if actually will be in 10s bootlegging takes the string direct access?

Perfect ideas

Based on the above problem, can be more asynchronous verification, write a list, the access to the string is placed in the list, the subsequent access to the list is compared to the next, if within this list, access is denied.

The design ideas above can solve the problem.

Optimized

The final design idea can certainly solve the problem, but there is also a problem, that is, as time progresses, the access list will be more and more large, is always unfriendly. You definitely need to design a time-out for the string.

Visited_list = ['28g12b12128912e2kj|127381237812391'  829312g12be120e102ej12je91|12312984123123',....]

If the above-mentioned way to take the system time comparison is of course a very laborious work, occupy a lot of Io, you can use Redis to easily achieve this function.

CBV through this kind of decoration way to achieve validation

Validation code

defApi_auth_method (Request): Auth_key= Request. Meta.get ('Http_auth_key')    if  notAuth_key:returnFalse SP= Auth_key.split ('|')    ifLen (sp)! = 2:        returnFalse Encrypt, timestamp=sp Timestamp=float (timestamp) Limit_timestamp= Time.time ()-Asset_auth_timePrint(Limit_timestamp, timestamp)ifLimit_timestamp >Timestamp:returnFalse ha= Hashlib.md5 (Asset_auth_key.encode ('Utf-8')) ha.update (bytes ("%s|%f"% (Asset_auth_key, timestamp), encoding='Utf-8') ) Result=ha.hexdigest ()Print(result, encrypt)ifEncrypt! =Result:returnFalse exist=False Del_keys= []     forKvinchEnumerate (encrypt_list):Print(k, v) m= v[' Time'] n= v['Encrypt']        ifM <Limit_timestamp:del_keys.append (k)Continue        ifn = =encrypt:exist=True forKinchDel_keys:delEncrypt_list[k]ifexist:returnFalse encrypt_list.append ({'Encrypt': Encrypt,' Time': Timestamp}) returnTruedefApi_auth (func):defInner (request, *args, * *Kwargs):if  notApi_auth_method (Request):returnJsonresponse ({'Code': 1001,'message':'API Authorization failed'}, json_dumps_params={'Ensure_ascii': False}) returnFunc (Request, *args, * *Kwargs)returnInner
Auth

Python API Simple Validation

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.