简体   繁体   English

传递 REST API 身份验证令牌在 PostMan 中工作但不是 Python 请求

[英]Passing REST API Authentication Token Working in PostMan But Not Python Requests

I'm trying to use Python Requests to access some information via a REST API.我正在尝试使用 Python 请求通过 REST API 访问一些信息。 The API that I am using requires authentication, and after a login request the response will contain a session ID that is then supposed to be included in the header of all future requests.我使用的 API 需要身份验证,并且在登录请求之后,响应将包含一个会话 ID,然后应该将其包含在所有未来请求的标头中。 The API documentation states: API 文档指出:

Once the authentication is successful, a JSON response with an access token is returned.身份验证成功后,将返回带有访问令牌的 JSON 响应。 The token needs to be set in the headers of all subsequent requests for them to be processed successfully.需要在所有后续请求的标头中设置令牌才能成功处理它们。 The API client should add an HTTP header with name "blabla_session_id", the same cookie name as in the Web Application API 客户端应添加名为“blabla_session_id”的 HTTP 标头,与 Web 应用程序中的 cookie 名称相同

I am able to successfully send a login request and receive a response with the session ID, however I am having trouble using Python Requests to add the session ID to the header.我能够成功发送登录请求并接收带有会话 ID 的响应,但是我在使用 Python 请求将会话 ID 添加到标头时遇到了问题。 I am using the following code:我正在使用以下代码:

# Functions

def login(base_url, username, password):
    print("Getting token...")
    header = {'content-type':'application/json'}

    data_get = {'email': username,
                'password':password,
                'workspaceId':12345678} 

    r = requests.post(base_url+'login', headers=header, json=data_get)

    if r.ok:
        print("Login Success!")
        global session_id   
        session_id = r.cookies['blabla_session_id']
        print("Session ID is %s" %session_id)

    else:
        print("Login Fail...")
        print("HTTP %i - %s, Message %s" % (r.status_code, r.reason, r.text))

def logout():
    header = {'blabla_session_id':session_id,'content-type':'application/json'}
    print (header)

    r = requests.put(base_url+'logout', headers=header)
    print (r.request.headers)

    if r.ok:
        print("Logout Success")
    else:
        print("Logout Failed")
        print("HTTP %i - %s, Message %s" % (r.status_code, r.reason, r.text))

def main():
    login(base_url, api_login, api_password)
    logout()

# Main Program
main()

When I execute this, I get the following response:当我执行此操作时,我得到以下响应:

Getting token...
Login Success!
Session ID is LABS-FReGnWuzzj7oYQ4nzPdvB55rOpctU48s%7C
{'blabla_session_id': 'LABS-FReGnWuzzj7oYQ4nzPdvB55rOpctU48s%7C', 'content-type': 'application/json'}
{'User-Agent': 'python-requests/2.25.1', 'Accept-Encoding': 'gzip, deflate', 'Accept': '*/*', 'Connection': 'keep-alive', 'blabla_session_id': 'LABS-FReGnWuzzj7oYQ4nzPdvB55rOpctU48s%7C', 'content-type': 'application/json', 'Content-Length': '0'}
Logout Failed
HTTP 401 - , Message {"status":401,"errors":[{"code":401,"message":"There is no access token associated with this request or the access token is not valid."}]}

Command Line Response命令行响应

Any ideas where I'm going wrong?任何想法我哪里出错了? As the title suggests, I did try using PostMan to verify the API and I am able to login, add the session ID to the header and logout without issue.正如标题所暗示的那样,我确实尝试使用 PostMan 来验证 API,并且我能够登录,将会话 ID 添加到标题并注销没有问题。 I suspect this has something to do with the format of the header, but I'm not sure.我怀疑这与标题的格式有关,但我不确定。

Move to using a single requests session and that will propagate particularly cookies across all your http actions ensuring that successful authentication is carried over into all requests.转向使用单个请求session ,这将在您的所有 http 操作中传播特别的 cookie,确保成功的身份验证传递到所有请求中。

For example:例如:

import requests

def login(s,base_url, username, password):
    print("Getting token...")
    header = {'content-type':'application/json'}

    data_get = {'email': username,
                'password':password,
                'workspaceId':12345678} 

    r = s.post(base_url+'login', headers=header, json=data_get)

    if r.ok:
        print("Login Success!")
        global session_id   
        session_id = r.cookies['blabla_session_id']
        print("Session ID is %s" %session_id)

    else:
        print("Login Fail...")
        print("HTTP %i - %s, Message %s" % (r.status_code, r.reason, r.text))

def logout(s):
    header = {'blabla_session_id':session_id,'content-type':'application/json'}
    print (header)

    r = s.put(base_url+'logout', headers=header)
    print (r.request.headers)

    if r.ok:
        print("Logout Success")
    else:
        print("Logout Failed")
        print("HTTP %i - %s, Message %s" % (r.status_code, r.reason, r.text))

def main():
    s = requests.session()
    login(s,base_url, api_login, api_password)
    logout(s)

# Main Program
main()

On your logout header there is no content-type.在您的注销标题上没有内容类型。 Might be the issue here!可能是这里的问题!

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

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