简体   繁体   English

Python 带身份验证的请求 (access_token)

[英]Python request with authentication (access_token)

I am trying to use an API query in Python. From the command line I can use curl like so:我正在尝试在 Python 中使用 API 查询。从命令行我可以像这样使用curl

curl --header "Authorization:access_token myToken" https://website.example/id

This gives some JSON output. myToken is a hexadecimal variable that remains constant throughout.这给出了一些 JSON myToken是一个始终保持不变的十六进制变量。

I would like to make this call from python so that I can loop through different ids and analyze the output. Before authentication was needed I had done that with urllib2 .我想从 python 进行此调用,以便我可以循环遍历不同的 ID 并分析 output。在需要身份验证之前,我已经使用urllib2完成了该操作。 I have also taken a look at the requests module but couldn't figure out how to authenticate with it.我也查看了requests模块,但不知道如何使用它进行身份验证。

The requests package has a very nice API for HTTP requests, adding a custom header works like this ( source: official docs ): requests包有一个非常好的用于 HTTP 请求的 API,添加自定义标头的工作方式如下( 来源:官方文档):

>>> import requests
>>> response = requests.get(
... 'https://website.example/id', headers={'Authorization': 'access_token myToken'})

If you don't want to use an external dependency, the same thing using urllib2 of the standard library looks like this ( source: the missing manual ):如果您不想使用外部依赖项,使用标准库的 urllib2 相同的东西看起来像这样( 来源:缺失的手册):

>>> import urllib2
>>> response = urllib2.urlopen(
... urllib2.Request('https://website.example/id', headers={'Authorization': 'access_token myToken'})

I had the same problem when trying to use a token with Github.尝试在 Github 中使用令牌时,我遇到了同样的问题。

The only syntax that has worked for me with Python 3 is:在 Python 3 中对我有用的唯一语法是:

import requests

myToken = '<token>'
myUrl = '<website>'
head = {'Authorization': 'token {}'.format(myToken)}
response = requests.get(myUrl, headers=head)
>>> import requests
>>> response = requests.get('https://website.com/id', headers={'Authorization': 'access_token myToken'})

If the above doesnt work , try this:如果上述方法不起作用,请尝试以下操作:

>>> import requests
>>> response = requests.get('https://api.buildkite.com/v2/organizations/orgName/pipelines/pipelineName/builds/1230', headers={ 'Authorization': 'Bearer <your_token>' })
>>> print response.json()
import requests

BASE_URL = 'http://localhost:8080/v3/getPlan'
token = "eyJhbGciOiJSUzI1NiIsImtpZCI6ImR"

headers = {'Authorization': "Bearer {}".format(token)}
auth_response = requests.get(BASE_URL, headers=headers)

print(auth_response.json())

Output :输出 :

{
"plans": [
    {
        "field": false,
        "description": "plan 12",
        "enabled": true
    }
  ]
}

Have you tried the uncurl package ( https://github.com/spulec/uncurl )?您是否尝试过uncurl包( https://github.com/spulec/uncurl )? You can install it via pip, pip install uncurl .您可以通过 pip、 pip install uncurl安装它。 Your curl request returns:您的 curl 请求返回:

>>> uncurl "curl --header \"Authorization:access_token myToken\" https://website.com/id"

requests.get("https://website.com/id",
    headers={
        "Authorization": "access_token myToken"
    },
    cookies={},
)

I'll add a bit hint: it seems what you pass as the key value of a header depends on your authorization type, in my case that was PRIVATE-TOKEN我将添加一点提示:您作为标头的键值传递的内容似乎取决于您的授权类型,在我的情况下是PRIVATE-TOKEN

header = {'PRIVATE-TOKEN': 'my_token'}
response = requests.get(myUrl, headers=header)

A lot of good answers already, but I didn't see this option yet:已经有很多好的答案,但我还没有看到这个选项:

If you're using requests , you could also specify a custom authentication class, similar to HTTPBasicAuth .如果您使用requests ,您还可以指定自定义身份验证类,类似于HTTPBasicAuth For example:例如:

from requests.auth import AuthBase


class TokenAuth(AuthBase):
    def __init__(self, token, auth_scheme='Bearer'):
        self.token = token
        self.auth_scheme = auth_scheme

    def __call__(self, request):
        request.headers['Authorization'] = f'{self.auth_scheme} {self.token}'
        return request

This could be used as follows (using the custom auth_scheme from the example):这可以按如下方式使用(使用示例中的自定义auth_scheme ):

response = requests.get(
    url='https://example.com', 
    auth=TokenAuth(token='abcde', auth_scheme='access_token'),
)

This may look like a more complicated way to set the Request.headers attribute, but it can be advantageous if you want to support multiple types of authentication.这可能看起来像是一种更复杂的设置Request.headers属性的方法,但如果您想支持多种类型的身份验证,它可能会很有优势。 Note this allows us to use the auth argument instead of the headers argument.请注意,这允许我们使用auth参数而不是headers参数。

One of the option used in python to retrieve below: python 中使用的选项之一检索以下内容:

import requests

token="abcd" < retrieved based>
headers = {'Authorization': "Bearer {}".format(token)}
response = requests.get(
    'https://<url api>',
    headers=headers,
    verify="root ca certificate"
)

print(response.content)

If you get hostname mismatch error then additional SANs need to be configured in the server with the hostnames.如果您收到主机名不匹配错误,则需要使用主机名在服务器中配置其他 SAN。

Hope this helps.希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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