我试图用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错误。请提出建议。在
看来您没有正确传递用户名和密码来进行身份验证。您应该从
auth
变量中获得username
和password
的值。因此,请尝试将requires_auth
函数改为:这是烧瓶授权的一个工作示例。在
我的请求文件:
^{pr2}$如果在本地主机上运行此程序,则应使用本地主机地址。
你的
<abc.com>
是什么代码。可能吧这就是错误。在编辑2
以下是一些方法,可以帮助您开始使用基于令牌的身份验证。在
我所做的是
username
和password
是否正确之后,可以使用gen_token
方法生成令牌。您可以根据需要修改此方法。Read Hereusername
。password
可以留空,也可以在该位置发送{SECRET_KEY
来加载它。可以根据您的要求处理异常。如果令牌有效,您将能够获得发送请求的用户,从而执行您的过程。在希望有帮助!在
查看这个link以获得更详细的解释。在
相关问题 更多 >
编程相关推荐