看了很多的資料,發現大家都是寫Vue與SpringBoot簡單前后分離demo,但目前我們保存用戶狀態時是需要token參與進來,
本文章僅介紹思路,具體實作代碼會在一段時間后更新成一個開源框架供大家學習,
token,顧名思義,令牌,
而令牌需要誰發送,當然是檢查的一方
所以下面我簡單寫一下關于前后端分離專案中,token的設計思路
1.在用戶初次訪問,檢測是否存在token,如果不存在token,那么進行賬戶密碼的校驗,如果存在token,那么后臺發送token到Vue前端,前端在localStorage中進行狀態保存
2.由于Vue已經進行狀態保存,所以每次獲取用戶資訊時,只需要對Token里的資訊進行提取即可
3.時效性,可以通過timeout設定超時時間,以此來控制賬戶的時效性保存
4.每次訪問后端都需要把token放在請求頭中,這樣每次訪問都可以判斷token是否生效
5.如果不生效,跳轉登錄界面
要在之前解決掉跨域的問題
module.exports = {
publicPath: '/admin',
devServer: {
port: 8080,
disableHostCheck: true,
proxy: {
'^/api': {
target: 'http://www.目標域名',
changeOrigin: true, // 將主機標頭的原點更改為目標URL
pathRewrite: {
'^/api': '/' //代理的路徑
}
},
}
},
}
首先我們說第一步,登錄部分,沿用了上述我們第一部分的思路,先校驗,后接收,再保存
onSubmit() {
this.form.validateFields((err) => {
if (!err) {
this.logging = true;
let code = this.form.getFieldValue("name");
let password = this.form.getFieldValue("password");
//記住我
if (this.checked) {
this.$store.dispatch("setLoginForm", {
code: code,
pass: password,
checked: this.checked,
});
} else {
this.$store.dispatch("setLoginForm", {});
}
// const encrypt = new JSEncrypt();
// encrypt.setPublicKey(this.publicKey);
// password = encrypt.encrypt(password);
signIn({
username: code,
password: password,
checkNum: this.form.getFieldValue("checkNum"),
deviceId: this.deviceId,
}).then((res) => {
this.logging = false;
if (res.rsCode == 0) {
this.$ls.set("token", res.obj.token, 8 * 60 * 60 * 1000);
this.$store.dispatch("保存位置", res.obj);
this.$router.push("/路由位置");
this.$notification["warning"]({
message: "用戶登錄成功!",
description: timeFix() + ",歡迎回來!",
});
} else {
this.handleToggleCode();
this.error = res.rsMsg;
}
});
}
});
}
現在我們將3.4部合并,設定時效性,每次訪問也都把token放在了頭部
const service = axios.create({
baseURL: BASE_URL, // api base_url
timeout: 60000, // 請求超時時間
transformRequest: [
function(data) {
var ret = "";
for (let it in data) {
ret +=
encodeURIComponent(it) + "=" + encodeURIComponent(data[it]) + "&";
}
const token = Vue.ls.get("token");
if (token) {
ret += "token=" + encodeURIComponent(token);
}
return ret;
},
],
});
最后只需要實作,token失效對其進行重新登錄
const err = (error) => {
if (error.response) {
const data = error.response.data;
const token = Vue.ls.get("token");
if (error.response.status === 403) {
notification.error({
message: "拒絕訪問",
});
}
if (
error.response.status === 401 &&
!(data.result && data.result.isLogin)
) {
notification.error({
message: "用戶未授權",
description: "用戶登錄超時,請重新登錄!",
});
if (token) {
//退出操作并轉向登錄頁
Vue.ls.clear();
//這里我在路由當中是做了設定,如果token為慷訓進入到登錄頁,所以只需要清除即可
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/250637.html
標籤:其他
上一篇:SpringBoot+SpringSecurity+JWT實作認證和授權
下一篇:2021初探博客,砥礪前行!!!
