Java的新项目学成在线笔记-day17(七)

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 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>[/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]
注意:其它前端系统要接入认证要请求认证服务也需要配置上边的代理路径。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值