Python请求库如何使用单个令牌传递授权标头 [英] Python requests library how to pass Authorization header with single token

查看:129
本文介绍了Python请求库如何使用单个令牌传递授权标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  curl -s< MY_URI> -H授权:TOK:< MY_TOKEN> 

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

pre $ 导入sys,套接字
导入请求

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

我已经尝试过:

  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>'))

但这些都不起作用。

解决方案

在python中:

 ('< MY_TOKEN>')

相当于

 '< MY_TOKEN> '

请求解释

 ('TOK','< MY_TOKEN>')

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

 'VE9LOjxNWV9UT0tFTj4K'

这是'TO的base64表示K:< MY_TOKEN>'



为了传递你自己的头文件,你需要像下面这样传递字典:

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


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

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:

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.

解决方案

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>'

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

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

这篇关于Python请求库如何使用单个令牌传递授权标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆