简体   繁体   中英

Flask Rest API - How to use Bearer API token in python requests

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.

Python code used for Flask API:

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

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

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!"}

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)

It shows error: Unauthorized Access 401

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

Thanks in advance!

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.

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

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

curl -u uses not bearer tokens but BasicAuth (via login and password). Try this:

url = 'http://%s:%s@127.0.0.1:5000/api/resource' % (
    'eyJhbGciOiJIUzI1NiIsImlhsfsdfsdzNCwiZXhwIjoxNTMwNzksdfsdsdRF.eyJpZCI6MX0.YhZvjKiafmv-qrvAxVo7UKQuohS2vkF-9scpuqsKRuw',
    'sp',
)
headers = {
    'Content-Type': 'application/json',
}
response = requests.request("GET", url, headers=headers)

But the recommended way is passing login and password encoded in header :

import base64
url = 'http://127.0.0.1:5000/api/resource'
headers = {
    'Content-Type': 'application/json',
    'Authorization': 'Basic %s' % base64.b64encode('%s:%s' % (
            'eyJhbGciOiJIUzI1NiIsImlhsfsdfsdzNCwiZXhwIjoxNTMwNzksdfsdsdRF.eyJpZCI6MX0.YhZvjKiafmv-qrvAxVo7UKQuohS2vkF-9scpuqsKRuw',
            'sp',
        ),
    ),
}
response = requests.request("GET", url, headers=headers)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM