我正在尝试在 session 过期后实现自动注销,但我无法做到这一点,我尝试实现超时以及 cookies 过期时间,但它不起作用,这是我的所有代码。这是登录 API https://digitalfleet.eu/api/1/oauth/token/
,
我正在尝试在 session 过期后实现自动注销,但我无法做到这一点,我尝试实现超时以及 cookies 过期时间,但它不起作用,这是我的所有代码。这是登录 API https://digitalfleet.eu/api/1/oauth/token/
,
componentDidMount() {
this.redirect();
}
handleSubmit(e) {
e.preventDefault();
let authToken = localStorage.getItem("Token");
axios({
// Define Method
method: "post",
// Set Access Token URL
url: config.apiUrl.login,
//Set Headers
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Authorization: "Bearer " + JSON.parse(authToken)
},
// Interpolate variables in the strings using Template Literals
data: `grant_type=${GRANT_TYPE}&username=${this.state.username}&password=${this.state.password}&client_id=${CLIENT_ID}`
})
.then(response => {
// console.log(response.data);
// Save All Data in localstorage
var ls = require("local-storage");
this.cookies = new Cookies();
ls.set("Token", response.data["access_token"]);
this.cookies.set("Token", response.data["access_token"], {
path: "/",
expires: new Date(Date.now() + 2592000)
});
ls.set("RefreshToken", response.data["refresh_token"]);
ls.set("Toke Type", response.data["token_type"]);
ls.set("Token Scope", response.data["scope"]);
ls.set("Expire in", response.data["expires_in"]);
// Used swal alert
Swal.fire({
title: "Log in",
type: "success",
text: "You Successfully loggedin",
showConfirmButton: false,
timerProgressBar: true,
timer: 3000
});
this.redirect();
})
.catch(response => {
//handle error
console.log(response);
Swal.fire({
title: "Login Error",
type: "error",
text: "Please Enter Correct Username and Password",
timerProgressBar: true,
timer: 3000
});
});
}
redirect() {
if (ls.get("Token")) {
this.props.history.push("/dashboard");
window.location.reload();
}
}
这是注销代码
onLogout() {
localStorage.clear();
// window.localStorage.clear();
this.props.history.push("/");
window.location.reload();
}
最佳答案
在 this.redirect()
中,您正在检查 LocalStorage
中的 token ,但您已在 cookie 中设置了 token 的过期时间(而不是在本地存储中)
此外,无法在本地存储中设置过期时间。直接使用cookie或通过lscache之类的服务控制本地存储数据
关于javascript - react js : How to Get Automatically Logout After Session Expired?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59412364/