我使用Python flask开发了一个HTTP REST API,它托管在Amazon Elastic Beanstalk(平台:Python 3.4)上。为了保护API,我想为它添加基本身份验证。
第一种方法是直接在Python应用程序中添加Basic Auth(如here所述)。这需要通过在.ebextensions目录中添加.conf文件来启用身份验证转发:
container_commands:
01_wsgipass:
command: 'echo "WSGIPassAuthorization On" >> ../wsgi.conf'
第二种方法是通过在.ebextensions目录中添加.config文件来配置Elastic Beanstalk容器。我从here获得了以下配置。但这不适合我。
files:
"/etc/httpd/conf.d/allow_override.conf":
mode: "000644"
owner: ec2-user
group: ec2-user
encoding: plain
content: |
<Directory /opt/python/current/app/>
AllowOverride AuthConfig
</Directory>
"/etc/httpd/conf.d/auth.conf":
mode: "000644"
owner: ec2-user
group: ec2-user
encoding: plain
content: |
<Directory /opt/python/current/app/>
AuthType Basic
AuthName "My Application"
AuthUserFile /etc/httpd/.htpasswd
Require valid-user
</Directory>
"/etc/httpd/.htpasswd":
mode: "000644"
owner: ec2-user
group: ec2-user
encoding: plain
content: |
appuser:pw1234
将基本身份验证添加到Python API的最佳方法是什么(在以后可能添加SSL的情况下)如果是第二个,为什么.conf文件无效。
答案 0 :(得分:0)
有几种方法可以去。
Flask有一个HTTP基本身份验证示例。 http://flask.pocoo.org/snippets/8/
from functools import wraps
from flask import request, Response
from sqlalchemy import create_engine # database connection for users table
from sqlalchemy.orm import sessionmaker
engine = create_engine('postgresql://username:password@localhost/dbname')
Session = sessionmaker(bind=some_engine)
session = Session()
def check_auth(username, password):
# query users table (probably want to hash the password or something)
return session.query(Users).filter_by(username=username, password=password).first() is not None
def authenticate():
"""Sends a 401 response that enables basic auth"""
return Response(
'Could not verify your access level for that URL.\n'
'You have to login with proper credentials', 401,
{'WWW-Authenticate': 'Basic realm="Login Required"'})
def requires_auth(f):
@wraps(f)
def decorated(*args, **kwargs):
auth = request.authorization # checks authorization headers -> Authorization: username="me" password="12345"
if not auth or not check_auth(auth.username, auth.password):
return authenticate()
return f(*args, **kwargs)
return decorated
这允许您在任何函数(可能只是端点)上使用@requires_auth装饰器,它将检查从客户端发送的授权标头。您不必使用sqlalchemy,但它经常与Flask一起使用。
或者...... Auth0可以通过它们进行身份验证。我不为他们工作,也不想为他们做广告;我过去刚刚使用它,效果很好。
https://auth0.com/docs/server-apis/python
祝你好运!