2.3 前端请求jwt 2.3.1 需求分析 前端需求如下: 用户登录成功,前端请求认证服务获取jwt令牌。 前端解析jwt令牌的内容,得到用户信息,并将用户信息存储到sessionStorage。 从 sessionStorage取出用户信息在页头显示用户名称。 2.3.2 API方法 在login.js中定义getjwt方法: [mw_shl_code=applescript,true]/获取jwt令牌/ const getjwt = () => { return requestGet('/openapi/auth/userjwt'); }[/mw_shl_code] 2.3.3 页面 修改include/header.html 1、页面视图

[mw_shl_code=applescript,true]<span v‐if="logined == true">欢迎{{this.user.username}}</span> <a rel="nofollow" href="javascript:;" @click="logout" v‐if="logined == true">退出</a> <a rel="nofollow" href="http://ucenter.xuecheng.com/" class="personal" target="_blank">我的学习</a> <a rel="nofollow" href="javascript:;" @click="showlogin" v‐if="logined == false">登陆 | 注册</a> <a rel="nofollow" href="http://teacher.xuecheng.com/" class="personal" target="_blank">教学提供方</a> <a rel="nofollow" href="http://system.xuecheng.com/" class="personal" target="_blank">系统后台</a>[/mw_shl_code] 用户登录成功设置数据对象logined为true,设置数据对象user为当前用户信息。 数据对象定义如下:

[mw_shl_code=applescript,true]user:{
userid:'',
username: '', userpic: '' }, logined:false [/mw_shl_code] 2、解析jwt令牌 在util.js中定义解析jwt令牌方法:

[mw_shl_code=applescript,true]//解析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; } [/mw_shl_code] 3、refresh_user() 在mounted钩子方法中获取当前用户信息,并将用户信息存储到sessionStorage

[mw_shl_code=applescript,true]mounted(){
//刷新当前用户
this.refresh_user() }[/mw_shl_code] refresh_user()方法如下:

[mw_shl_code=applescript,true]refresh_user:function(){
//从sessionStorage中取出当前用户
let activeUser= getActiveUser();
//取出cookie中的令牌 let uid = getCookie("uid")[/mw_shl_code] [mw_shl_code=applescript,true]//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))
}
}
})
}
}[/mw_shl_code] 2.3.4 配置代理转发 上边实现在首页显示当前用户信息,首页需要通过Nginx代理请求认证服务,所以需要在首页的虚拟主机上配置代 理路径:

[mw_shl_code=applescript,true]#认证 location ^~ /openapi/auth/ {
proxy_pass http://auth_server_pool/auth/;
}[/mw_shl_code] 注意:其它前端系统要接入认证要请求认证服务也需要配置上边的代理路径。