Skip to content

Flask服务JWT Demo

依赖环境

toml
[tool.poetry.dependencies]
python = "^3.8"
Flask = "^2.1.1"
Flask-RESTful = "^0.3.9"
Flask-Cors = "^3.0.10"
Flask-JWT-Extended = "^4.3.1"

代码

python
from flask import Flask
from flask_restful import Api
from flask_cors import CORS
from flask_jwt_extended import JWTManager
from datetime import timedelta

from handlers.auth import Login
from handlers.index import Index

app = Flask(__name__)
app.config["JWT_SECRET_KEY"] = 'MY2022&token'
app.config["JWT_COOKIE_SECURE"] = False
app.config["JWT_BLACKLIST_ENABLED"] = True
app.config["JWT_BLACKLIST_TOKEN_CHECKS"] = ['access', 'refresh']
app.config["JWT_ACCESS_TOKEN_EXPIRES"] = timedelta(days=7)

jwt = JWTManager(app)
api = Api(app)
cors = CORS(app, resources={"*": {"origins": "*"}}, supports_credentials=True)

api.add_resource(Login, '/login')
api.add_resource(Index, '/index')

if __name__ == '__main__':
    app.run()
python
from flask import request
from flask_restful import Resource
from flask_jwt_extended import create_access_token
from auth.auth import UserModel

user_model = UserModel()

class Login(Resource):

    def post(self):
        try:
            payload_data = request.json
            username = payload_data.get('username')
            password = payload_data.get('password')
            user = user_model.find_by_username(username)
            if user and user_model.check_password(user, password):
                access_token = create_access_token(identity=user, fresh=True)

                return dict(code=1, message="ok", data=dict(
                    access_token=access_token
                )), 200
            else:
                return dict(code=0, message="error auth", data=None), 200
        except:
            return dict(code=0, message="error params", data=None), 404
python
from flask_restful import Resource
from flask_jwt_extended import jwt_required

class Index(Resource):

    @jwt_required()
    def get(self):
        return dict(
            status=200,
            msg="ok",
            data="ok"
        )

Released under the MIT License.