本文介绍了Flask Rest API-如何在python请求中使用Bearer API令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我已经在Flask中开发了一个API,并使用了基本的身份验证令牌.当我使用curl测试此API时,则接受了承载令牌,并且API正常工作.但是在python请求中使用时,它显示401错误.

I have developed an API in Flask and using basic authentication token. When I testing this API with curl then bearer token accepted and API is working. But when using in python requests it is showing 401 error.

用于Flask API的Python代码:

Python code used for Flask API:

@app.route('/api/resource')
@auth.login_required
def get_resource():
    return

jsonify({'data':'你好,%s!'%g.user.username.title()})

jsonify({'data': 'Hello, %s!' % g.user.username.title()})

使用curl进行测试可以正常工作:>

Testing with curl is working fine:>

curl -u eyJhbGciOiJIUzI1NsdfCI6MTUzMDc5MDIzNCwiZXhwIjoxNT
   MwNzkwODM0fQ.eyJpZCsf.jKiafmv-qrvAxVo7UKQuohS2vkF-9scpuqsKRuw:sp -i -X GET
   http://127.0.0.1:5000/api/resource
   HTTP/1.0 200 OK
   Content-Type: application/json
Content-Length: 32
Server: Werkzeug/0.14.1 Python/3.6.4
Date: Thu, 05 Jul 2018 11:33:22 GMT
{  "data": "Hello, FlaskAPI!"}

使用API​​的Python代码:

Python code to consume API:

import requests
url = "http://127.0.0.1:5000/api/resource"
headers = {
    'Content-Type': "application/json",
    'Authorization': "Bearer eyJhbGciOiJIUzI1NiIsImlhsfsdfsdzNCwiZXhwIjoxNTMwNzksdfsdsdRF.eyJpZCI6MX0.YhZvjKiafmv-qrvAxVo7UKQuohS2vkF-9scpuqsKRuw"
    }

response = requests.request("GET", url, headers=headers)

print(response.text)

它显示错误:未经授权的访问401

It shows error:Unauthorized Access 401

如何使用Python或邮递员在curl中使用的Bearer令牌?

How to use Bearer token used in curl from Python or postman?

提前谢谢!

推荐答案

如果您希望我们使用不记名令牌,请看看Miguel Grinberg的应用程序编程接口,然后向下滚动到用户模型中的令牌"".但是,整个事情值得一读.

If you want us to use Bearer tokens take a look at Miguel Grinberg's Application Programming Interfaces and scroll down to the "Tokens in the User Model". However, the whole thing deserves a read.

另一篇文章是Real Pythons的令牌基于Flask的身份验证.

Another article is Real Pythons's Token-Based Authentication with Flask.

这两种方法都将有助于理解和实施承载令牌.

Both of these will help with understanding and implementation of bearer tokens.

这篇关于Flask Rest API-如何在python请求中使用Bearer API令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 15:59