Flask中的JWT认证

HTTP认证方式:

  • Basic
  • Bearer
  • JWT(JSON Web Token)

JWT的结构:

Section name meaning
HEADER The first part stores the type of token and the encryption algorithm
PAYLOAD The second part has the data that identifies the user: it can be its ID, user name, etc.
SIGNATURE Digital signature, which is generated with the previous two sections, and it allows you to verify if the content has been modified.

示例Python代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# -*- coding: utf-8 -*-
# @place: Pudong, Shanghai
# @contact: lianmingjie@shanda.com
# @file: jwt_test.py
# @time: 2023/7/4 17:29
from flask import Flask, jsonify, request

from flask_jwt_extended import create_access_token
from flask_jwt_extended import get_jwt_identity
from flask_jwt_extended import jwt_required
from flask_jwt_extended import JWTManager

app = Flask(__name__)

# 设置 Flask-JWT-Extended 插件的秘钥
app.config["JWT_SECRET_KEY"] = "super-secret" # 设置 jwt 的秘钥
jwt = JWTManager(app)


# 创建一个路由来验证登录的用户并返回JWT
# create_access_token() 函数用来生成实际的JWT token.
@app.route("/login", methods=["POST"])
def login():
username = request.json.get("username", None)
password = request.json.get("password", None)
if username not in ["admin1", "admin2", "admin3"] or password != "123456":
return jsonify({"msg": "Bad username or password"}), 401

# 传入身份信息创建 access_token
access_token = create_access_token(identity=username)
return jsonify(access_token='Bearer ' + access_token)


# 使用 jwt_required 保护请求视图,如果在请求中不存在jwt token将无法访问。
@app.route("/protected", methods=["GET"])
@jwt_required()
def protected():
# 使用 get_jwt_identity 访问当前用户的身份
current_user = get_jwt_identity()
return jsonify(logged_in_as=current_user), 200


if __name__ == "__main__":
app.run(debug=True)

创建JWT:

1
2
3
4
5
6
curl --location 'http://127.0.0.1:5000/login' \
--header 'Content-Type: application/json' \
--data '{
"username": "admin3",
"password": "123456"
}'

验证JWT:

1
2
curl --location 'http://127.0.0.1:5000/protected' \
--header 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJmcmVzaCI6ZmFsc2UsImlhdCI6MTY4ODQ2Mzg5OCwianRpIjoiZDU1NDdjMGQtZjc2Zi00MTA3LThhNTAtYWZmN2I4NTIxMzEzIiwidHlwZSI6ImFjY2VzcyIsInN1YiI6ImFkbWluMyIsIm5iZiI6MTY4ODQ2Mzg5OCwiZXhwIjoxNjg4NDY0Nzk4fQ.hFUJNHF9ULv_tWK31ttOhHMp_-azevG6VyJRsiUcMcM'

Flask中的JWT认证
https://percent4.github.io/Flask中的JWT认证/
作者
Jclian91
发布于
2023年7月10日
许可协议