token 设置及其刷新

//测试token
//获取token
function setToken(data){
var storage = window.localStorage;
if(!storage){
alert("浏览器不支持localstorage");
return false;
}
var token = data.access_token;
storage.setItem("user_token", token);
storage.setItem("user_login_time", new Date().getTime());//保存登录时间
}
function getToken()
{
var storage = window.localStorage;

var current = new Date().getTime();//拿token的时间
console.log("拿token的时间"+old_time)
var token = storage.user_token;//token的值

var old_time = storage.user_login_time;//登录的时间
console.log("登陆的时间"+old_time)
var time = (current - old_time) /1000;//时间差
console.log("时间差"+time)
var out_time = 3600;// 超时设置
var parse_time = 24 * 60 * 60;// 刷新设置
// debugger
// //手动清除缓存
// var length = window.localStorage.length;
// if(length==0){
// window.location.href = "login.html"
// }
//超时
if(parse_time > time && time >= out_time) {
refreshToken(token);
}
//1天过期 重新登录
if(time >= parse_time) {
window.location.href = "login.html";
}
return token;
}
function headerSetup(token)
{
$.ajaxSetup({
'headers':{
'Authorization': 'Bearer '+ token,
}
});
}
//刷新token
function refreshToken(token)
{
if(window.localStorage.length==0){
window.localStorage.clear();
window.location.href = "login.html";
}
$.ajaxSetup({
'headers': {
'Authorization': 'Bearer ' + token,
}
});
$.ajax({
url:"http://ezist.cn/api/authorizations/current",
type:'post',
dataType: "json",
data: {},
success: function(data) {
setToken(data);
},
error: function (data) {
console.log("数据请求失败");
window.location.href='login.html';
}
});
}

猜你喜欢

转载自www.cnblogs.com/chanhxy/p/9376833.html
今日推荐