后端开发环境
Flask 2.2.2
Flask-Cors 3.0.10
Flask-HTTPAuth 4.5.0
Flask-RESTful 0.3.9
itsdangerous 2.0.1
代码目录结构
D:.
│
├─utils
│ │ token_auth.py
│ └─__init__.py
│
├─views
│ │ login.py
│ │ upload.py
│ └─__init__.py
│
│ app.py
└─ config.py
后端代码
1、自定义认证token的方法
文件位置: utils/token_auth.py
from flask_httpauth import HTTPTokenAuth
from itsdangerous import TimedJSONWebSignatureSerializer
from config import secret_key
# 用于生成token
s = TimedJSONWebSignatureSerializer(secret_key,expires_in=28800)
auth = HTTPTokenAuth()
# 认证客户端传递过来的token是否正确,前端请求中的headers中需要添加'Authorization'
@auth.verify_token
def verify_token(token):
try:
data = s.loads(token)
except Exception as e:
print("【login】认证异常",e,flush=True)
return False
return True
@auth.error_handler
def unauthorized():
return {"code": 50000, "data": f"403:认证异常,请重新登录!"}, 200
2、登录接口
views/login.py
from flask import Blueprint
from flask_restful import reqparse, Resource, Api
from config import admin_passwd, secret_key
from utils.token_auth import auth
from itsdangerous import TimedJSONWebSignatureSerializer
s = TimedJSONWebSignatureSerializer(secret_key,expires_in=28800)
blueprint = Blueprint('login',__name__)
api = Api(blueprint)
parser = reqparse.RequestParser()
parser.add_argument('username',type=str)
parser.add_argument('password',type=str)
class User(Resource):
@auth.login_required
def get(self, user_opt):
if user_opt == 'info':
return {
"code": 20000,
"data": {"roles": ["admin"],"name": "admin","avatar": "/sl.png"}}
# 生成token
def post(self, user_opt):
if user_opt == 'login':
args = parser.parse_args()
username = args.get('username')
password = args.get('password')
if password == admin_passwd and username == "admin":
// 通过s.dumps(admin_passwd)来生成token
token = str(s.dumps(admin_passwd),encoding="utf-8")
return {"code": 20000,"data": {"token": "Bearer {}".format(token)}}
else:
return {"code": 40000, "data": "密码错误!"}
elif user_opt == 'logout':
return {"code": 20000,"data": "success"}
api.add_resource(User, '/api/user/<user_opt>')
3、启动文件内容
app.py
from flask import Flask
from flask_restful import Api
from flask_cors import CORS
from views import upload,login
app = Flask(__name__)
cors = CORS(app, resources={r"/api/*": {"origins": "*"}})
app.register_blueprint(upload.blueprint)
app.register_blueprint(login.blueprint)
if __name__ == '__main__':
app.run(host = '0.0.0.0', debug=True)
配置文件
config.py
import os
# 设置默认的key值
secret_key = os.environ.get('secret_key','0a79caed-8a45-49b9-97a6-86e50e12b234')
# 设置默认的登录密码
admin_passwd = os.environ.get('admin_passwd','123456')
前端部分
前端直接用的开源的vue-admin-template
github仓库地址: https://github.com/PanJiaChen/vue-admin-template
src/api/user.js
这一部分是用于控制用户登录以及退出的接口
import request from '@/utils/request'
export function login(data) {
return request({
url: '/api/user/login',
method: 'post',
data
})
}
export function getInfo(token) {
return request({
url: '/api/user/info',
method: 'get',
params: { token }
})
}
export function logout() {
return request({
url: '/api/user/logout',
method: 'post'
})
}
src/utils/request.js
需要将请求头的字段改成Authorization,与后端认证相关请求头匹配
前后端整体编译以及部署
目录结构
项目所有代码
https://gitee.com/scc205/sdam.git