jwt.js
用到的base64.js 和 hmac-sha256.js 在我的资源文档里里
import Base64 from './base64.js' // npm 也有,具体忘记名字了
import CryptoJS from './hmac-sha256.js' //可以直接npm install CryptoJS
let keys4=Base64.encoder('xxxxxxxx') // 秘钥
export default {
jwt(payload, key =(Base64.decoder(keys4))) {
if (this.isJSON(payload)) {
if (typeof payload == 'object') {
payload = JSON.stringify(payload)
}
let header = '{"typ":"JWT","alg":"HS256"}'
let headerBase64 = Base64.encoder(header)
let payloadBase64 = Base64.encoder(payload)
let base64Token = headerBase64 + '.' + payloadBase64
let signature = CryptoJS.HmacSHA256(base64Token, key)
let signatureBase64 = Base64.hexToBase64(signature.toString())
let jwt = base64Token + '.' + signatureBase64
// console.log(jwt,'加密00000')
return jwt;
}else {
throw '请传入正确的JSON字符串'
}
}, isJSON(str) {
if (typeof str === 'string') {
try {
JSON.parse(str)
return true
} catch(e) {
return false
}
}else if (typeof str === 'object') {
try {
return true
} catch(e) {
return false
}
}
}
}
api.js 使用jwt 加密数据
import axios from 'axios'
import jwt from './_Jwt'
import request from './request'
var commonParam = {
"android_id": "xxxx",
"dtp": "Android",
"chn": "normal",
"av": "1.0.2",
"userId": "xx",
"device_id": "xxxxx",
"umId": "xxxxx"
} // 一些公共参数,无用
// commonParam = jwt.jwt(commonParam)
console.log(commonParam,'commonParam')
axios.interceptors.request.use(function (config) {
config.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8'
config.headers['commonParam'] = jwt.jwt(commonParam)
config.data = jwt.jwt(config.data || {})
return config
})
axios.interceptors.response.use(response => response,
err => Promise.resolve({
data: {
status: 500,
message: '网络异常,请检测您的网络',
}
}))
// 获取用户信息 ,试用的加密数据调用接口
export const getList = (data) => axios.post('/miyoo-dev/api/clock/ClockDetail', data).then(res => res.data)