Reputation: 618
I have a question about basic Auth using Flask / flask-restful. I've been trying to figure out the best way to do this. Currently I have a small program, it contains one resource that has some very simple JSON.
Since this is just a personal tool, I only have one user: me. I have some devices that poll this route, and grab that JSON, then parse it to do other things. Most of the tutorials and examples I find are dealing with multiple users, logins, blogs, user registration with databases, etc, which makes sense but its kind of overkill for what I am doing.
What is the simplest way to set up some basic auth, in flask, for one route that will only ever be used by one person?
Upvotes: 2
Views: 3845
Reputation: 618
Ok! I found something that will suit my needs for now. I'm just leaving it here. Obviously you don't want to slap USER_DATA in there like that, but for the sake of "just figuring it out", its there.
http://polyglot.ninja/securing-rest-apis-basic-http-authentication-python-flask/
from flask import Flask
from flask_restful import Resource, Api
from flask_httpauth import HTTPBasicAuth
app = Flask(__name__)
api = Api(app, prefix="/api/v1")
auth = HTTPBasicAuth()
USER_DATA = {
"admin": "SuperSecretPwd"
}
@auth.verify_password
def verify(username, password):
if not (username and password):
return False
return USER_DATA.get(username) == password
class PrivateResource(Resource):
@auth.login_required
def get(self):
return {"meaning_of_life": 42}
api.add_resource(PrivateResource, '/private')
if __name__ == '__main__':
app.run(host='0.0.0.0',debug=True, use_reloader=False)
Upvotes: 2