cookieDomain: xuecheng.com
@Api(value = "jwt查询接口",description = "客户端查询jwt令牌内容")
public interface AuthControllerApi {
@ApiOperation("查询userjwt令牌")
public JwtResult userjwt();
....
//从redis查询令牌
public AuthToken getUserToken(String token){
String userToken = "user_token:"+token;
String userTokenString = stringRedisTemplate.opsForValue().get(userToken);
if(userToken!=null){
AuthToken authToken = null;
try {
authToken = JSON.parseObject(userTokenString, AuthToken.class);
} catch (Exception e) {
LOGGER.error("getUserToken from redis and execute JSON.parseObject error
{}",e.getMessage());
e.printStackTrace();
}
return authToken;
}
return null;
}
@Override
@GetMapping("/userjwt")
public JwtResult userjwt() {
//获取cookie中的令牌
String access_token = getTokenFormCookie();
//根据令牌从redis查询jwt
AuthToken authToken = authService.getUserToken(access_token);
if(authToken == null){
return new JwtResult(CommonCode.FAIL,null);
}
return new JwtResult(CommonCode.SUCCESS,authToken.getJwt_token());
}
//从cookie中读取访问令牌
private String getTokenFormCookie(){
Map<String, String> cookieMap = CookieUtil.readCookie(request, "uid");
String access_token = cookieMap.get("uid");
return access_token;
}
/*获取jwt令牌*/
const getjwt = () => {
return requestGet('/openapi/auth/userjwt');
}
<span v‐if="logined == true">欢迎{{this.user.username}}</span>
<a href="javascript:;" @click="logout" v‐if="logined == true">退出</a>
<a href="http://ucenter.xuecheng.com/" class="personal" target="_blank">我的学习</a>
<a href="javascript:;" @click="showlogin" v‐if="logined == false">登陆 | 注册</a>
<a href="http://teacher.xuecheng.com/" class="personal" target="_blank">教学提供方</a>
<a href="http://system.xuecheng.com/" class="personal" target="_blank">系统后台</a>
user:{
userid:'',
username: '',
userpic: ''
},
logined:false
//解析jwt令牌,获取用户信息
var getUserInfoFromJwt = function (jwt) {
if(!jwt){
return ;
}
var jwtDecodeVal = jwt_decode(jwt);
if (!jwtDecodeVal) {
return ;
}
let activeUser={}
//console.log(jwtDecodeVal)
activeUser.utype = jwtDecodeVal.utype || '';
activeUser.username = jwtDecodeVal.name || '';
activeUser.userpic = jwtDecodeVal.userpic || '';
activeUser.userid = jwtDecodeVal.userid || '';
activeUser.authorities = jwtDecodeVal.authorities || '';
activeUser.uid = jwtDecodeVal.jti || '';
activeUser.jwt = jwt;
return activeUser;
}
mounted(){
//刷新当前用户
this.refresh_user()
}
refresh_user:function(){
//从sessionStorage中取出当前用户
let activeUser= getActiveUser();
//取出cookie中的令牌
let uid = getCookie("uid")
//console.log(activeUser)
if(activeUser && uid && uid == activeUser.uid){
this.logined = true
this.user = activeUser;
}else{
if(!uid){
return ;
}
//请求查询jwt
getjwt().then((res) => {
if(res.success){
let jwt = res.jwt;
let activeUser = getUserInfoFromJwt(jwt)
if(activeUser){
this.logined = true
this.user = activeUser;
setUserSession("activeUser",JSON.stringify(activeUser))
}
}
})
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |