安全的Python REST api

2024-09-30 06:26:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用python编写一些restapi,首先我开始编写身份验证代码。我在其中一个网站上找到了身份验证的示例代码:

from functools import wraps
from flask import request, Response

def check_auth(username, password):
    """This function is called to check if a username /
    password combination is valid.
    """
    return username == 'admin' and password == 'secret'

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
        if not auth or not check_auth(username, password):
            return authenticate()
        return f(*args, **kwargs)
    return decorated

我已使用上述代码保护我的示例应用程序:

^{pr2}$

python/curl正在尝试通过这个模块调用python/curl。但是,无论用户名/密码是否有效,每次它都会返回401错误。在

使用请求:

import requests, base64
usrPass = "admin:secret"
b64Val = base64.b64encode(usrPass)
from requests.auth import HTTPBasicAuth
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
res = requests.get('https://<abc.com>/student/1', auth=HTTPBasicAuth('admin','secret'), headers={'Authorization': 'Basic %s' % b64Val}, data={}, verify=False)
print res

使用卷曲:

myCurlPut = pycurl.Curl()
myCurlPut.setopt(pycurl.URL, "https://<abc.com>/student/1")
myCurlPut.setopt(pycurl.HTTPAUTH, pycurl.HTTPAUTH_BASIC)
myCurlPut.setopt(pycurl.USERPWD, "%s:%s" % ('admin', 'secret'))
myCurlPut.setopt(pycurl.SSL_VERIFYPEER, 0)
myCurlPut.setopt(pycurl.HTTPHEADER, ['X-HTTP-Method-Override: GET'])
myCurlPut.perform()

可以,任何人请帮助我为什么每次它都返回401错误。请提出建议。在


Tags: 代码fromimportauthsecretreturnadmindef
2条回答

看来您没有正确传递用户名和密码来进行身份验证。您应该从auth变量中获得usernamepassword的值。因此,请尝试将requires_auth函数改为:

def requires_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        auth = request.authorization
        if not auth or not check_auth(auth.username, auth.password):
            return authenticate()
        return f(*args, **kwargs)
    return decorated

这是烧瓶授权的一个工作示例。在

from functools import wraps

from flask import Flask,Response,request, abort


app = Flask(__name__)

def check_auth(name,passw):
    return (name=='admin' and passw=='pass')

def requires_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        auth = request.authorization
        if not auth or not check_auth(auth.username, auth.password):
            abort(401)
        return f(*args, **kwargs)
    return decorated


@app.route('/')
@requires_auth
def hello():
    return "Hello World"


if __name__ == "__main__":
    app.run(debug=True)

我的请求文件:

^{pr2}$

如果在本地主机上运行此程序,则应使用本地主机地址。
你的<abc.com>是什么代码。可能吧这就是错误。在

编辑2

from itsdangerous import TimedJSONWebSignatureSerializer as Serializer, BadSignature, SignatureExpired


def gen_token(name,passw, expiration=None):
    s = Serializer(app.config['SECRET_KEY'], expires_in = expiration)
    return s.dumps(name, passw)

def verify_token(token):
    serial = Serializer(app.config['SECRET_KEY'])
    try:
        data = serial.loads(token)
    except BadSignature:
        return "Error"
    except SignatureExpired:
        return "Error"

    name = data[0]
    passw = data[1]

    return name,passw

以下是一些方法,可以帮助您开始使用基于令牌的身份验证。在

我所做的是

  1. 用户通过在Auth头中发送用户名和密码的请求从服务器请求令牌
  2. 在检查usernamepassword是否正确之后,可以使用gen_token方法生成令牌。您可以根据需要修改此方法。Read Here
  3. 现在,用户将从方法2接收到的令牌发送到Auth头中的usernamepassword可以留空,也可以在该位置发送{}。在
  4. 当您收到令牌时,您需要使用SECRET_KEY来加载它。可以根据您的要求处理异常。如果令牌有效,您将能够获得发送请求的用户,从而执行您的过程。在

希望有帮助!在

查看这个link以获得更详细的解释。在

相关问题 更多 >

    热门问题