前端登陆代码实现:
<script>
// 前台用户名密码
let username = 'shimily',
password = 'xlx444444'
// 后台私钥
let priKey = 'mi2019longer@12345'
// 加密密码
function encrypt(str) {
let cipher = new JSEncrypt()
cipher.setPublicKey(priKey)
return cipher.encrypt(str)
}
// 登陆数据
let data = {
username: username,
password: encrypt(password)
}
// 将数据发送到后端鉴权
axios.post('/xxx', data)
.then(res => {
console.log(res)
})
</script>
后端代码实现:
#安装RSA模块
pip install sanic-rsa
#解密代码
from sanic_rsa import Rsa
def decrypt(token):
'''
解密接口
'''
#私钥,用于解密
PRI_KEY = 'mi2019longer@12345'
#实例化RSA
rsa = Rsa(PRI_KEY)
#解密token中的数据
password = rsa.decrypt(token)
return password
#服务端的鉴权代码
@app.route('/xxx', method='POST')
def authenticate():
#获取前端传来的登陆信息
username = request.json.get('username')
password = request.json.get('password')
#解密密码
token = decrypt(password)
#校验账号密码
if username == 'shimily' and token == 'xlx444444':
return json({"code":0, "msg": "success"})
return json({"code":1, "msg": "数据不匹配,认证失败"})