简体   繁体   English

用 Python 编写客户端以使用 JWT 身份验证调用休息 Web 服务

[英]write a client in Python to call a rest web service using JWT authentication

I have setup a Django REST endpoint with JSON Web Tokens (JWT) Authentication, following all the steps explained in this article .我已经按照本文中解释的所有步骤设置了一个带有 JSON Web 令牌 (JWT) 身份验证的 Django REST 端点。

Briefly, the exposed endpoints are:简而言之,暴露的端点是:

  • http://localhost:8000/api/token/ # to get a new jwt token http://localhost:8000/api/token/ # 获取新的 jwt 令牌
  • http://localhost:8000/api/token/refresh/ # to refresh a jwt token http://localhost:8000/api/token/refresh/ # 刷新一个 jwt 令牌
  • http://localhost:8000/hello/ # a sample web service which requires jwt authentication http://localhost:8000/hello/ # 需要 jwt 身份验证的示例 Web 服务

The example explained in the article uses djangorestframework_simplejwt package, which uses settings.SECRET_KEY (of the Django web app) to encrypt the jwt tokens (using HS256 algorithm).文章中解释的示例使用 djangorestframework_simplejwt 包,该包使用 settings.SECRET_KEY(Django Web 应用程序的)来加密 jwt 令牌(使用 HS256 算法)。

Also, server side, I have created a specific username ("testuser") with Django administration website to be used for JWT authorization.另外,在服务器端,我在 Django 管理网站上创建了一个特定的用户名(“testuser”),用于 JWT 授权。

Now, how can I start testing this REST web service which uses JWT authentication with a client written in Python?现在,我如何开始测试这个使用 JWT 身份验证的 REST Web 服务和一个用 Python 编写的客户端?

To start testing the sample web service:要开始测试示例 Web 服务:

first, the client needs to get a new token, thus I introduce do_auth function, which returns a dictionary containing JWT 'access' and 'refresh' tokens:首先,客户端需要获取一个新的令牌,因此我引入了 do_auth 函数,它返回一个包含 JWT 'access' 和 'refresh' 令牌的字典:

import json
import requests

AUTH_API_ENDPOINT = "http://localhost:8000/api/token/"
REFRESH_TOKEN_API_ENDPOINT = "http://localhost:8000/api/token/refresh/"


def do_auth(username, password, url=AUTH_API_ENDPOINT) -> dict:
    data = {
        "username": username,
        "password": password
    }

    # sending post request and saving response as response object
    r = requests.post(url=url, data=data)

    # extracting response text
    response_text = r.text

    d = json.loads(response_text)

    return d

After successfully getting the 'access' and 'refresh' tokens (I need the correct credentials to do that ie I need to define a User in Django administration site), I can use the 'access' token to call the 'hello' end point:成功获得“访问”和“刷新”令牌后(我需要正确的凭据才能做到这一点,即我需要在 Django 管理站点中定义一个用户),我可以使用“访问”令牌来调用“hello”端点:

def do_get(url, access_token: str):
    headers = {
        'Authorization': ('Bearer ' + access_token)
    }

    response = requests.get(url, headers=headers)

    return response

thus, to make a first call to the web service:因此,要首次调用 Web 服务:

token_dict = do_auth("testuser", ...testuser password... )
# check response status code (should be 200 if successful)

# now I can call the endpoint
response = do_get('http://localhost:8000/hello', token_dict['access'])
# check response status code (should be 200 if successful)

print(response)
print(response.status_code) # error 401 : not authenticated

that's all to start testing the new web service.这就是开始测试新 Web 服务的全部内容。

JWT also provides for token refresh, so you will need also something like this: JWT 还提供令牌刷新,因此您还需要以下内容:

def do_refresh(refresh_token, url=REFRESH_TOKEN_API_ENDPOINT):
    data = {
        'refresh': refresh_token
    }

    r = requests.post(url=url, data=data)

    d = json.loads(r.text)

    return d

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

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