3、在utils.js中添加 如下方法
[AppleScript] 纯文本查看 复制代码
?
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | getActiveUser : function ( ) { let uid = this.getCookie ( "uid" ) if ( uid ) { let activeUserStr = this.getUserSession ( "activeUser" ) ; return JSON.parse ( activeUserStr ) ; } else { this.delUserSession ( "activeUser" ) } } , / / 获取jwt令牌 getJwt : function ( ) { let activeUser = this.getActiveUser ( ) if ( activeUser ) { return activeUser.jwt } } , / / 解析jwt令牌,获取用户信息 getUserInfoFromJwt : function ( jwt ) { if ( !jwt ) { return ; } var jwtDecodeVal = jwtDecode ( 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; } , |
4、测试 1)启动学习中心前端、教学管理前端、认证服务、用户中心服务、网关、Eureka
a、进入首页 b、点击“教学提供方”,此时由于没有登录自动跳转到登录页面
4.2.2 携带JWT授权
1、前端携带JWT请求
根据需求,在使用axios进行http请求前向header中加入jwt令牌 在main.js中添加
[AppleScript] 纯文本查看 复制代码
?
1 2 3 4 5 6 7 8 | import axios from 'axios' / / 添加请求拦截器 axios.interceptors.request.use ( function ( config ) { / / 在发送请求向header添加jwt let jwt = utilApi.getJwt ( ) if ( jwt ) { config.headers['Authorization'] = 'Bearer ' + jwt } return config; } , function ( error ) { return Promise.reject ( error ) ; } ) ; |
2、测试http请求是否携带jwt
进入教学管理中心,点击我的课程,观察request header中是否有Authorization信息
3、测试授权效果
当访问一个没有权限的方法时是否报错?
测试方法:
在课程计划查询方法上添加授权注解,表示当前用户需要拥有course_teachplan_list权限方可正常访问。
[AppleScript] 纯文本查看 复制代码
?
1 2 3 | @PreAuthorize ( "hasAuthority('course_teachplan_list')" ) @Override public TeachplanNode findTeachplanList ( @PathVariable ( "courseId" ) String courseId ) { return courseService.findTeachplanList ( courseId ) ; } |
进入我的课程,点击课程计划,观察响应结果为 10002错误。
4、提示权限不足
当权限不足首页要给出提示,实现思路是使用axios的拦截,在执行后校验响应结果,如果是10002代码的错误则 提示用户“权限不足”,如果是10001代码则强制登录。 在main.js中添加
[AppleScript] 纯文本查看 复制代码
?
01 02 03 04 05 06 07 08 09 10 11 12 13 14 | @PreAuthorize ( "hasAuthority('course_teachplan_list')" ) @Override public TeachplanNode findTeachplanList ( @PathVariable ( "courseId" ) String courseId ) { return courseService.findTeachplanList ( courseId ) ; } / / 响应拦截 axios.interceptors.response.use ( data = > { console. log ( "data=" ) console. log ( data ) if ( data & & data . data ) { if ( data . data .code & & data . data .code = = ' 10001 ' ) { / / 需要登录 window . location = "http://ucenter.xuecheng.com/#/login?returnUrl=" + Base 64. encode ( window . location ) } else if ( data . data .code & & data . data .code = = ' 10002 ' ) { Message. error ( '您没有此操作的权限,请与客服联系! ' ) ; } |
[AppleScript] 纯文本查看 复制代码
?
测试:
执行一个没有权限的操作,提示如下: