add authentication

This commit is contained in:
Martin
2016-05-11 16:05:42 +02:00
parent f41a16f041
commit 9ced739ef6
3 changed files with 28 additions and 3 deletions
+9 -1
View File
@@ -28,7 +28,15 @@ List of available configuration options:
| Name | Description |
| ---- | ----------- |
| `SQLALCHEMY_DATABASE_URI` | Database connection string. e.g: `postgresql://user:password@localhost/photowall` |
| `DEBUG` | Enable/disable debug mode
| `DEBUG` | Enable/disable debug mode |
| `API_KEYS` | A list of api keys that are used to authenticate to the API
## Authentication
Authentication to the API is performed via HTTP Basic Auth. The user should provide her API key as the basic auth username parameter. An example request in cURL looks like this (adding a colon after the username prevents cURL from asking for a password):
```
$ curl http://localhost:5000/designers/ -u mykey:
```
API keys should be added to the `API_KEYS` configuration option
## Getting started
+17 -1
View File
@@ -1,4 +1,4 @@
from flask import Flask, jsonify
from flask import Flask, jsonify, Response, request
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
@@ -17,6 +17,22 @@ from api.views import designers
app.register_blueprint(designers.mod)
def check_authentication():
auth = request.authorization
if not auth:
return False
return auth.username in app.config.get("API_KEYS")
@app.before_request
def authenticate():
if not check_authentication():
return Response(
'No valid API key provided', 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'}
)
@app.route("/")
def index():
data = {
+2 -1
View File
@@ -1,3 +1,4 @@
SQLALCHEMY_DATABASE_URI = 'postgresql://user:password@host/db_name'
SQLALCHEMY_TRACK_MODIFICATIONS = True
DEBUG = True
DEBUG = True
API_KEYS = ['secretkey']