HTTP-API authentication, Python implementation

The title is relatively vague, but this article is to introduce how to use python to encrypt the api interface of http to prevent illegal use of criminals. Here are a few premise that need to be explained. First of all, we have to implement http encryption authentication, so we do not consider https. Secondly, the purpose of authentication is to allow an http api interface to be used by the correct (authenticated) person, rather than any.

Design

Understand the purpose of http api authentication, then come to design!

The most lazy solution

I have written several API interfaces before, mainly used to transfer some database data. Because the data is sensitive, I use authentication. At that time, in order to be lazy, the authentication method was particularly simple and simple, that is, an auth field was added to the api interface, and the content of the field was verified on the server side, but the content was a string of written md5. Although this is also a way of authentication (friends who don’t know the contents of the auth field can’t get the data of the api interface), if the traffic on the LAN is monitored, then this kind of scheme will be ineffective.

Simple and practical design

A better design solution is to implement a set of encryption algorithms on the client side and the server side. The algorithm can be customized but is more complicated. If the parameters and content of the request are arranged in a certain way, you can add a timestamp and do a hash operation as a whole. The server will also get the parameters of the hash, and compare it with the hash passed by the client. Because of the timestamp, even if traffic is being monitored, traffic replay cannot be successfully authenticated. (because of differences in timestamps)

  • Explain: This article describes an authentication method for api, which is different from the authentication of the website. Mainly depends on the application scenario of the api. If it is called to internal personnel, and there are not many users called, the above authentication scheme is sufficient. Because the key used for encryption can be sent to the user in other secure ways (even on paper, 2333), instead of using asymmetric encryption + symmetric encryption, and using digital certificates, etc., like the https protocol. A series of complex encryption authentication methods. *

Ok, the previous article introduced some api authentication schemes, then write something later? I am not going to introduce how to develop a code for a certification scheme. I mainly want to recommend an open source project —hawk, because it is used to implement http encryption authentication, and it has a python implementation module (mohawk), recommended It is because it is simple and practical.

Because I have studied the mohawk module for 2 hours (really 2 hours), this article mainly introduces the usage of mohawk. In the enterprise, the api encryption authentication scheme is generally designed by itself (generally, a token ciphertext is generated, and a strict two-factor authentication is performed). Therefore, this module is suitable for beginners to practice hands, and can also provide for friends who intend to design their own authentication schemes. An idea. The following is some of the basic usages of my review of the mohawk documentation. For more details, please refer to the official website documentation.

hawk Introduction

Hawk project address: https://github.com/hueniverse/hawk
Python implementation: https://github.com/kumar303/mohawk
Official documentation: https://mohawk.readthedocs.io/en/latest/

Installing hawk

1
pip install mohawk

Building a webserver

Here I use python’s falcon framework to build an api webserver. If you are unfamiliar with the falcon framework, you can read it first: https://thief.one/2017/11/27/1/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
import falcon
From mohawk import Receiver # Import the Receiver method of the mohawk module
from wsgiref import simple_server
allowed_senders={
"test":{
'id': 'test',
'key': '110',
'algorithm': 'sha256'
}, # test user group
"nmask":{
'id': 'nmask',
'key': '112',
'algorithm': 'sha256'
}, # nmask User Group
}
def lookup_credentials(sender_id):
''' Verify that the user is within the allowed range '''
if sender_id in allowed_senders:
return allowed_senders[sender_id]
else:
raise LookupError('unknown sender')
class Test(object):
def on_post(self, req, resp):
''' http post method '''
try:
Receiver(
lookup_credentials,
Req.headers.get('AUTHORIZATION'), #key generated at request
req.url,
req.method,
content= req.stream.read(),
content_type=req.headers.get('CONTENT-TYPE')
)
except Exception,e:
''' An error indicates that the authentication failed '''
print is
resp.status = falcon.HTTP_403 # This is the default status
else:
resp.status = falcon.HTTP_200 # This is the default status
resp.body = ('Hello World!')
def on_get(self, req, resp):
''' http get method '''
try:
Receiver(
lookup_credentials,
req.headers.get('AUTHORIZATION'),
req.url,
req.method,
content= req.stream.read(),
content_type=req.headers.get('CONTENT-TYPE')
)
except Exception,e:
print is
resp.status = falcon.HTTP_403 # This is the default status
resp.body = ('authorization fail!')
else:
resp.status = falcon.HTTP_200 # This is the default status
resp.body = ('Hello World!')
app = falcon.API()
test = Test()
app.add_route('/', test)
if __name__ == '__main__':
httpd = simple_server.make_server('127.0.0.1', 8000, app)
httpd.serve_forever()

Building an http request

After building the webserver, we naturally need to build the http request to verify whether the request has gone through the authentication process, and the result of the authentication is correct. Here we use the requests package to build.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import json
import requests
From mohawk import Sender # Import the modder module's Sender method
url = "http://127.0.0.1:8000/"
Post_data = json.dumps("") # If it is a get request, the parameter content can be set to ""
content_type = 'application/x-www-form-urlencoded'
# dictionary for authentication
credentials = {
'id': 'test',
'key': '10',
'algorithm': 'sha256'
}
sender = Sender(credentials,
Url = url, # required
Method = 'POST', # required
Content = post_data, # required, if it is a get request, the parameter content can be set to ""
Content_type = content_type # required
)
Print sender.request_header # generated ciphertext, passed to the server as a header
res=requests.post(
url = url,
data = post_data,
headers={
'Authorization': sender.request_header,
'Content-Type': content_type
}
)
print res.status_code
print res.text

mohawk module description

Mohawk is the python python implementation, there are several main methods: Sender, Receiver, etc., you can read the source code in detail.

The Sender method is used to generate the password required for http request authentication. This method needs to pass several parameters, such as: url, method, content(post_data), content_type, credentials (certified dictionary, including id, key, encryption method). ), this method will generate a ciphertext password based on the passed parameter values, and then we can pass it to the server in the headers.

The Receiver method is used to receive the request sent by the client on the server, and calculate a new cipher text password according to the content of the obtained parameter, and compare it with the ciphertext transmitted by the client to achieve the authentication effect.

本文标题:HTTP-API authentication, Python implementation

文章作者:nmask

发布时间:2017年12月11日 - 16:12

最后更新:2019年07月11日 - 18:07

原始链接:https://thief.one/2017/12/11/1/en/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

nmask wechat
欢迎您扫一扫上面的微信公众号,订阅我的博客!
坚持原创技术分享,您的支持将鼓励我继续创作!

热门文章推荐: