Python请求库如何使用单个令牌传递授权标头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19069701/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:42:35  来源:igfitidea点击:

Python requests library how to pass Authorization header with single token

pythongetauthorizationtokenpython-requests

提问by

I have a request URI and a token. If I use:

我有一个请求 URI 和一个令牌。如果我使用:

curl -s "<MY_URI>" -H "Authorization: TOK:<MY_TOKEN>"

etc., I get a 200 and view the corresponding JSON data. So, I installed requests and when I attempt to access this resource I get a 403 probably because I do not know the correct syntax to pass that token. Can anyone help me figure it out? This is what I have:

等等,我得到一个200并查看相应的JSON数据。因此,我安装了请求,当我尝试访问此资源时,我得到 403,可能是因为我不知道传递该令牌的正确语法。谁能帮我弄清楚吗?这就是我所拥有的:

import sys,socket
import requests

r = requests.get('<MY_URI>','<MY_TOKEN>')
r. status_code

I already tried:

我已经尝试过:

r = requests.get('<MY_URI>',auth=('<MY_TOKEN>'))
r = requests.get('<MY_URI>',auth=('TOK','<MY_TOKEN>'))
r = requests.get('<MY_URI>',headers=('Authorization: TOK:<MY_TOKEN>'))

But none of these work.

但这些都不起作用。

采纳答案by Ian Stapleton Cordasco

In python:

在蟒蛇中:

('<MY_TOKEN>')

is equivalent to

相当于

'<MY_TOKEN>'

And requests interprets

并请求解释

('TOK', '<MY_TOKEN>')

As you wanting requests to use Basic Authentication and craft an authorization header like so:

当您希望请求使用基本身份验证并制作授权标头时,如下所示:

'VE9LOjxNWV9UT0tFTj4K'

Which is the base64 representation of 'TOK:<MY_TOKEN>'

哪个是 base64 表示 'TOK:<MY_TOKEN>'

To pass your own header you pass in a dictionary like so:

要传递您自己的标题,您需要传入一个字典,如下所示:

r = requests.get('<MY_URI>', headers={'Authorization': 'TOK:<MY_TOKEN>'})

回答by BajajG

I was looking for something similar and came across this. It looks like in the first option you mentioned

我正在寻找类似的东西并遇到了这个。看起来像你提到的第一个选项

r = requests.get('<MY_URI>', auth=('<MY_TOKEN>'))

"auth" takes two parameters: username and password, so the actual statement should be

“auth”有两个参数:用户名和密码,所以实际语句应该是

r=requests.get('<MY_URI>', auth=('<YOUR_USERNAME>', '<YOUR_PASSWORD>'))

In my case, there was no password, so I left the second parameter in auth field empty as shown below:

就我而言,没有密码,所以我将 auth 字段中的第二个参数留空,如下所示:

r=requests.get('<MY_URI', auth=('MY_USERNAME', ''))

Hope this helps somebody :)

希望这对某人有所帮助:)

回答by swatisinghi

You can try something like this

你可以试试这样的

r = requests.get(ENDPOINT, params=params, headers={'Authorization': 'Basic %s' %  API_KEY})

回答by Anton Tarasenko

You can also set headers for the entire session:

您还可以为整个会话设置标题:

TOKEN = 'abcd0123'
HEADERS = {'Authorization': 'token {}'.format(TOKEN)}

with requests.Session() as s:

    s.headers.update(HEADERS)
    resp = s.get('http://example.com/')

回答by Edgar N

This worked for me:

这对我有用:

access_token = #yourAccessTokenHere#

result = requests.post(url,
      headers={'Content-Type':'application/json',
               'Authorization': 'Bearer {}'.format(access_token)})

回答by Amit Blum

Requests natively supports basic auth only with user-pass params, not with tokens.

请求本身仅支持用户传递参数的基本身份验证,而不支持令牌。

You could, if you wanted, add the following class to have requests support token based basic authentication:

如果需要,您可以添加以下类以使请求支持基于令牌的基本身份验证:

import requests
from base64 import b64encode

class BasicAuthToken(requests.auth.AuthBase):
    def __init__(self, token):
        self.token = token
    def __call__(self, r):
        authstr = 'Basic ' + b64encode(('token:' + self.token).encode('utf-8')).decode('utf-8')
        r.headers['Authorization'] = authstr
        return r

Then, to use it run the following request :

然后,要使用它运行以下请求:

r = requests.get(url, auth=BasicAuthToken(api_token))

An alternative would be to formulate a custom header instead, just as was suggested by other users here.

另一种方法是制定自定义标题,正如其他用户在这里建议的那样。

回答by Tri Tran

i founded here, its ok with me for linkedin: https://auth0.com/docs/flows/guides/auth-code/call-api-auth-codeso my code with with linkedin login here:

我在这里成立,它可以与我一起使用linkedin:https: //auth0.com/docs/flows/guides/auth-code/call-api-auth-code所以我的代码与linkedin登录:

ref = 'https://api.linkedin.com/v2/me'
headers = {"content-type": "application/json; charset=UTF-8",'Authorization':'Bearer {}'.format(access_token)}
Linkedin_user_info = requests.get(ref1, headers=headers).json()

回答by Reymond Joseph

This worked for me:

这对我有用:

r = requests.get('http://127.0.0.1:8000/api/ray/musics/', headers={'Authorization': 'Token 22ec0cc4207ebead1f51dea06ff149342082b190'})

My code uses user generated token.

我的代码使用用户生成的令牌。