标签归档:authorization

Python请求库如何通过单个令牌传递Authorization标头

问题:Python请求库如何通过单个令牌传递Authorization标头

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

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

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

import sys,socket
import requests

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

但是这些都不起作用。

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.


回答 0

在python中:

('<MY_TOKEN>')

相当于

'<MY_TOKEN>'

并要求翻译

('TOK', '<MY_TOKEN>')

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

'VE9LOjxNWV9UT0tFTj4K'

这是base64的表示形式 'TOK:<MY_TOKEN>'

要传递自己的标头,您需要像这样传递字典:

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

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

回答 1

我一直在寻找类似的东西,并且遇到了这个问题。看来您提到的第一个选项

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

“ auth”具有两个参数:用户名和密码,因此实际语句应为

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

在我的情况下,没有密码,因此我将auth字段中的第二个参数留空,如下所示:

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

希望这对某人有帮助:)

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

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:

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

Hope this helps somebody :)


回答 2

这为我工作:

access_token = #yourAccessTokenHere#

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

This worked for me:

access_token = #yourAccessTokenHere#

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

回答 3

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

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

with requests.Session() as s:

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

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

回答 4

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

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

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

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

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

一种替代方法是改为编写自定义标头,如此处其他用户所建议的那样。

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.


回答 5

我在这里建立了,我可以 在这里登录: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()

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

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

回答 6

您可以尝试这样的事情

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

You can try something like this

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

回答 7

这为我工作:

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

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

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.


如何在Flask中获取HTTP标头?

问题:如何在Flask中获取HTTP标头?

我是python的新手,使用Python Flask并生成REST API服务。

我想检查发送给客户端的授权标头。

但是我找不到在flask中获取HTTP标头的方法。

感谢获得HTTP标头授权的任何帮助。

I am newbie to python and using Python Flask and generating REST API service.

I want to check authorization header which is sent the client.

But I can’t find way to get HTTP header in flask.

Any help for getting HTTP header authorization is appreciated.


回答 0

from flask import request
request.headers.get('your-header-name')

request.headers 行为就像字典,因此您也可以像使用任何字典一样获取标头:

request.headers['your-header-name']
from flask import request
request.headers.get('your-header-name')

request.headers behaves like a dictionary, so you can also get your header like you would with any dictionary:

request.headers['your-header-name']

回答 1

请注意,如果标头不存在,则方法之间的区别是

request.headers.get('your-header-name')

将返回None或没有异常,因此您可以像使用它

if request.headers.get('your-header-name'):
    ....

但是以下内容将引发错误

if request.headers['your-header-name'] # KeyError: 'your-header-name'
    ....

你可以通过

if 'your-header-name' in request.headers:
   customHeader = request.headers['your-header-name']
   ....

just note, The different between the methods are, if the header is not exist

request.headers.get('your-header-name')

will return None or no exception, so you can use it like

if request.headers.get('your-header-name'):
    ....

but the following will throw an error

if request.headers['your-header-name'] # KeyError: 'your-header-name'
    ....

You can handle it by

if 'your-header-name' in request.headers:
   customHeader = request.headers['your-header-name']
   ....

回答 2

如果有人试图获取所有已传递的标头,则只需使用:

dict(request.headers)

它为您提供了dict中的所有标头,您实际上可以从中执行任何想要的操作。在我的用例中,由于python API是代理,因此我不得不将所有标头转发到另一个API

If any one’s trying to fetch all headers that were passed then just simply use:

dict(request.headers)

it gives you all the headers in a dict from which you can actually do whatever ops you want to. In my use case I had to forward all headers to another API since the python API was a proxy


回答 3

让我们看看如何在Flask中获取参数,标题和正文。我要在邮递员的帮助下进行解释。

参数项和值反映在API端点中。例如端点中的key1和key2:https : //127.0.0.1/uploadkey1 = value1&key2 = value2

from flask import Flask, request
app = Flask(__name__)

@app.route('/upload')
def upload():

  key_1 = request.args.get('key1')
  key_2 = request.args.get('key2')
  print(key_1)
  #--> value1
  print(key_2)
  #--> value2

在参数之后,让我们看看如何获​​取标题

  header_1 = request.headers.get('header1')
  header_2 = request.headers.get('header2')
  print(header_1)
  #--> header_value1
  print(header_2)
  #--> header_value2

现在让我们看看如何获​​得身体

  file_name = request.files['file'].filename
  ref_id = request.form['referenceId']
  print(ref_id)
  #--> WWB9838yb3r47484

因此我们使用request.files获取上传的文件,并使用request.form获取文本

Let’s see how we get the params, headers and body in Flask. I’m gonna explain with the help of postman.

The params keys and values are reflected in the API endpoint. for example key1 and key2 in the endpoint : https://127.0.0.1/upload?key1=value1&key2=value2

from flask import Flask, request
app = Flask(__name__)

@app.route('/upload')
def upload():

  key_1 = request.args.get('key1')
  key_2 = request.args.get('key2')
  print(key_1)
  #--> value1
  print(key_2)
  #--> value2

After params, let’s now see how to get the headers:

  header_1 = request.headers.get('header1')
  header_2 = request.headers.get('header2')
  print(header_1)
  #--> header_value1
  print(header_2)
  #--> header_value2

Now let’s see how to get the body

  file_name = request.files['file'].filename
  ref_id = request.form['referenceId']
  print(ref_id)
  #--> WWB9838yb3r47484

so we fetch the uploaded files with request.files and text with request.form