First make sure that you have the domain configurations saved as a Python file named settings.py in the same folder as your program. In this recipe, we have included a simple settings.py with the following content as a sample:
DOMAIN = {'people': {}}
If settings.py is not found, the program will halt with the following error:
eve.exceptions.ConfigException: DOMAIN dictionary missing or wrong.
Listing 11.9 gives a REST server with BasicAuth as follows:
#!/usr/bin/env python # Python Network Programming Cookbook, Second Edition
-- Chapter - 11 # This program is optimized for Python 2.7.12 and
Python 3.5.2. # It may run on any other version with/without
modifications. from eve import Eve from eve.auth import BasicAuth class MyBasicAuth(BasicAuth): def check_auth(self, username, password, allowed_roles,
resource, method): return username == 'admin' and password == 'secret' def run_server(): app = Eve(auth=MyBasicAuth) app.run() if __name__ == '__main__': run_server()
We run the server with the username admin and password secret.
$ python 20_9_eve_basic_auth.py * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
Assuming username admin and password secret, to retrieve the base64 encoded string of this credentials, you may use the following command:
$ echo -n admin:secret | base64 YWRtaW46c2VjcmV0
Now we run the client with the correct base64 encoded secret:
$ curl -H "Authorization: Basic YWRtaW46c2VjcmV0" -i http://127.0.0.1:5000 $ curl -H "Authorization: Basic YWRtaW46c2VjcmV0" -i http://127.0.0.1:5000 HTTP/1.0 200 OK Content-Type: application/json Content-Length: 62 Server: Eve/0.7.4 Werkzeug/0.11.15 Python/2.7.12 Date: Sat, 29 Jul 2017 12:10:04 GMT {"_links": {"child": [{"href": "people", "title": "people"}]}}
If you run curl with no credentials, the following output will be produced:
$ curl -i http://127.0.0.1:5000 HTTP/1.0 401 UNAUTHORIZED Content-Type: application/json Content-Length: 91 WWW-Authenticate: Basic realm="eve" Server: Eve/0.7.4 Werkzeug/0.11.15 Python/2.7.12 Date: Sat, 29 Jul 2017 12:09:02 GMT {"_status": "ERR", "_error": {"message": "Please provide proper credentials", "code": 401}}
The server will bring the following log to indicate the failed attempt:
127.0.0.1 - - [29/Jul/2017 14:09:02] "GET / HTTP/1.1" 401 -
The output for an attempt with wrong credentials would be similar to the preceding ones with no credentials:
curl -H "Authorization: Basic YV1" -i http://127.0.0.1:5000