调整d2crudplus接入flask登录

1,392次阅读
没有评论

共计 3145 个字符,预计需要花费 8 分钟才能阅读完成。

调整d2crudplus接入flask登录

出去飞了下,回来继续码,因为已有Go后端,只剩前端可以码了,但为了调试博主还是前后都码了吧

Flask内使用JWT

安装flask-jwt-extended库

pip install flask-jwt-extended

简单使用下

生成JWT

from flask_jwt_extended import create_access_token

@app.route("/login", methods=["POST"])
def login():
    username = request.json.get("username", None)
    password = request.json.get("password", None)
    if username != "test" or password != "test":
        return jsonify({"msg": "用户名或密码错误"}), 401

    access_token = create_access_token(identity=username)
    return jsonify(access_token=access_token)

验证JWT

# 使用jwt_required()装饰器在需要验证JWT的视图函数
from flask_jwt_extended import jwt_required

@app.route('/api/userinfo', methods=["GET"])
@jwt_required()
def userinfo():
    username = get_jwt_identity()
    return jsonify(logged_in_as=username), 200

刷新JWT

from flask_jwt_extended import create_access_token
from flask_jwt_extended import get_jwt_identity
from flask_jwt_extended import create_refresh_token

@app.route('/api/refresh', methods=["POST"])
@jwt_required(refresh=True)
def refresh():
    identity = get_jwt_identity()
    access_token = create_access_token(identity=identity)
    return jsonify(access_token=access_token)

一些参数

# 加密的salt
app.config['SECRET_KEY'] = "abcdefghijklmnopq"

# 设置过期时间
app.config['JWT_ACCESS_TOKEN_EXPIRES'] = datetime.timedelta(minutes=1)

# 设置refresh token过期时间
app.config["JWT_REFRESH_TOKEN_EXPIRES"] = datetime.timedelta(days=30)

完整的demo

from flask import Flask, request, jsonify
from flask_jwt_extended import JWTManager
from flask_jwt_extended import create_access_token
from flask_jwt_extended import jwt_required
from flask_jwt_extended import get_jwt_identity
from flask_jwt_extended import create_refresh_token
from flask_cors import CORS

import datetime

app = Flask(__name__)
jwt = JWTManager(app)
app.config['SECRET_KEY'] = "abcdefghijklmnopq"
app.config['JWT_ACCESS_TOKEN_EXPIRES'] = datetime.timedelta(minutes=1)
app.config["JWT_REFRESH_TOKEN_EXPIRES"] = datetime.timedelta(days=30)

CORS(app, resources=r'/*')
@app.route('/api/login', methods=['POST'])
def login():
    print(request.json)
    username = request.json.get("username", None)
    password = request.json.get("password", None)
    uuid = username + "uuid"
    if username != "test-admin" or password != "test-admin":
        return jsonify({
            "msg": "用户名或密码错误"
        }), 401
    access_token = create_access_token(identity=username)
    refresh_token = create_refresh_token(identity=username)

    response = {
        "code": 0,
        "msg": "登录成功",
        "data": {
            "token": access_token,
            "uuid": uuid,
            "username": username,
        }
    }
    return jsonify(response)


@app.route('/api/refresh', methods=["POST"])
@jwt_required(refresh=True)
def refresh():
    identity = get_jwt_identity()
    access_token = create_access_token(identity=identity)

    return jsonify(access_token=access_token)


@app.route('/api/userinfo', methods=["GET"])
@jwt_required()
def userinfo():
    username = get_jwt_identity()
    return jsonify(logged_in_as=username), 200


if __name__ == '__main__':
    app.run()

d2crudplus中接入

登录请求由模拟改为请求真实后端

// sys.user.js原本
SYS_USER_LOGIN (data = {}) {
    // 模拟数据
    mock
      .onAny('/login')
      .reply(config => {
        const user = find(users, tools.parse(config.data))
        return user
          ? tools.responseSuccess(assign({}, user, { token: faker.random.uuid() }))
          : tools.responseError({}, '账号或密码不正确')
      })
    // 接口请求
    return requestForMock({
      url: '/login',
      method: 'post',
      data
    })
  }

// 修改后
 SYS_USER_LOGIN (data = {}) {
    // 登录请求真实后端
    return request({
      url: '/login',   // 真实的后端地址 /api/login
      method: 'post',
      data
    })
  }

// .env调整,flask中博主做了跨域,不然会报错
# 网络请求公用地址
VUE_APP_API=http://127.0.0.1:5000/api/

正文完
 
xadocker
版权声明:本站原创文章,由 xadocker 2023-07-09发表,共计3145字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
评论(没有评论)