Java的接口调用时的权限验证功能的实现
作者:不给就捣乱 时间:2023-08-09 11:15:06
提示:这里可以添加本文要记录的大概内容:
例如:一般系统前端调用后台相关功能接口时,需要验证此时用户的权限是否满足调用该接口的条件,因此我们需要配置相应的验证权限的功能。
提示:以下是本篇文章正文内容,下面案例可供参考
一、编写的环境
工具:IDEA
框架:GUNS框架(自带后台权限验证配置,我们这里需要编写前端权限验证配置)
二、使用步骤
1.配置前端调用的接口
代码如下(示例):
在WebSecurityConfig中:
// 登录接口放开过滤
.antMatchers("/login").permitAll()
// session登录失效之后的跳转
.antMatchers("/global/sessionError").permitAll()
// 图片预览 头像
.antMatchers("/system/preview/*").permitAll()
// 错误页面的接口
.antMatchers("/error").permitAll()
.antMatchers("/global/error").permitAll()
// 测试多数据源的接口,可以去掉
.antMatchers("/tran/**").permitAll()
//获取租户列表的接口
.antMatchers("/tenantInfo/listTenants").permitAll()
//微信公众号接入
.antMatchers("/weChat/**").permitAll()
//微信公众号接入
.antMatchers("/file/**").permitAll()
//前端调用接口
.antMatchers("/api/**").permitAll()
.anyRequest().authenticated();
加入前端调用接口请求地址:
.antMatchers("/api/**").permitAll()
添加后前端所有/api的请求都会被拦截,不会直接调用相应接口
2.配置拦截路径
代码如下(示例):
在创建文件JwtlnterceptorConfig:
package cn.stylefeng.guns.sys.modular.bzjxjy.config.jwt;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class JwtInterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
//默认拦截所有路径
registry.addInterceptor(authenticationInterceptor())
.addPathPatterns("/api/**")
;
}
@Bean
public HandlerInterceptor authenticationInterceptor() {
return new JwtAuthenticationInterceptor();
}
}
3.创建验证文件
创建文件JwtAuthenticationInterceptor,代码如下(示例):
package cn.stylefeng.guns.sys.modular.bzjxjy.config.jwt;
import cn.stylefeng.guns.sys.modular.bzjxjy.entity.Student;
import cn.stylefeng.guns.sys.modular.bzjxjy.entity.TopTeacher;
import cn.stylefeng.guns.sys.modular.bzjxjy.enums.RoleEnum;
import cn.stylefeng.guns.sys.modular.bzjxjy.enums.StatusEnum;
import cn.stylefeng.guns.sys.modular.bzjxjy.exception.NeedToLogin;
import cn.stylefeng.guns.sys.modular.bzjxjy.exception.UserNotExist;
import cn.stylefeng.guns.sys.modular.bzjxjy.service.StudentService;
import cn.stylefeng.guns.sys.modular.bzjxjy.service.TopTeacherService;
import cn.stylefeng.guns.sys.modular.bzjxjy.util.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
/**
* jwt验证
* @author Administrator
*/
public class JwtAuthenticationInterceptor implements HandlerInterceptor {
@Autowired
private TopTeacherService topTeacherService;
@Autowired
private StudentService studentService;
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
// 如果不是映射到方法直接通过
if (!(object instanceof HandlerMethod)) {
return true;
}
HandlerMethod handlerMethod = (HandlerMethod) object;
Method method = handlerMethod.getMethod();
//检查是否有passtoken注释,有则跳过认证
if (method.isAnnotationPresent(PassToken.class)) {
PassToken passToken = method.getAnnotation(PassToken.class);
if (passToken.required()) {
return true;
}
}
//默认全部检查
else {
// 执行认证
Object token1 = httpServletRequest.getSession().getAttribute("token");
if (token1 == null) {
//这里其实是登录失效,没token了 这个错误也是我自定义的,读者需要自己修改
httpServletResponse.sendError(401,"未登录");
throw new NeedToLogin();
}
String token = token1.toString();
//获取载荷内容
String type = JwtUtils.getClaimByName(token, "type").asString();
String id = JwtUtils.getClaimByName(token, "id").asString();
String name = JwtUtils.getClaimByName(token, "name").asString();
String idNumber = JwtUtils.getClaimByName(token, "idNumber").asString();
//判断当前为名师
if (RoleEnum.TOP_TEACHER.equals(type)){
//检查用户是否存在
TopTeacher topTeacher = topTeacherService.getById(id);
if (topTeacher == null || topTeacher.getStatus().equals(StatusEnum.FORBIDDEN)) {
httpServletResponse.sendError(203,"非法操作");
//这个错误也是我自定义的
throw new UserNotExist();
}
//学生
}else {
//需要检查用户是否存在
Student user = studentService.getById(id);
if (user == null || user.getStatus().equals(StatusEnum.FORBIDDEN)) {
httpServletResponse.sendError(203,"非法操作");
//这个错误也是我自定义的
throw new UserNotExist();
}
}
// 验证 token
JwtUtils.verifyToken(token, id);
//放入attribute以便后面调用
httpServletRequest.setAttribute("type", type);
httpServletRequest.setAttribute("id", id);
httpServletRequest.setAttribute("name", name);
httpServletRequest.setAttribute("idNumber", idNumber);
return true;
}
return true;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
Object o, Exception e) throws Exception {
}
}
文件中有个string类型的token,这个token是用户登录时在controller里创建的,具体代码加在用户登陆的接口里:
String token = JwtUtils.createToken(topTeacher.getId(), RoleEnum.TOP_TEACHER,topTeacher.getName(),idNumber);
request.getSession().setAttribute("token",token);
4.创建注解@PassToken
package cn.stylefeng.guns.sys.modular.bzjxjy.config.jwt;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 在方法上加入本注解 即可跳过登录验证 比如登录
* @author Administrator
*/
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface PassToken {
boolean required() default true;
}
总结
提示:这里对文章进行总结:
以上就是完整的编写一个前端页面调用控制器接口时,进行验证判断相应权限的代码实现。主要是针对guns框架写的,因为guns框架本来自带接口权限验证功能,只不过只是针对后台而已,我在这里添加了针对前端的权限验证,仅供参考。
来源:https://blog.csdn.net/weixin_42632091/article/details/110069278
标签:Java,接口调用时,权限验证
0
投稿
猜你喜欢
Java实现过滤掉map集合中key或value为空的值示例
2021-05-25 10:26:17
Android简单实现 缓存数据
2022-11-04 11:30:54
Android RecyclerView网格布局示例解析
2023-03-04 00:49:44
Java实现的各种排序算法(插入排序、选择排序算法、冒泡排序算法)
2023-06-29 11:25:28
Android studio 快捷键大全
2022-03-27 14:58:56
C#调用WebService实例开发
2022-11-21 22:51:08
Android Studio报:“Attribute application@theme or @ icon ”问题的解决
2023-11-07 09:49:18
Android实现二级列表购物车功能
2022-08-28 09:26:28
C#实现多文件压缩与解压功能
2022-03-05 04:45:54
使用Springboot根据配置文件动态注入接口实现类
2022-11-18 06:56:45
C#控制台程序如何发布到服务器Linux上运行
2022-07-17 05:57:52
Java实现分页代码
2023-08-05 08:14:47
Java数据结构之红黑树的真正理解
2022-07-16 01:36:16
spring事务之事务挂起和事务恢复源码解读
2023-11-26 18:50:42
python gstreamer实现视频快进/快退/循环播放功能
2022-07-06 10:09:20
Java设计模式之接口隔离原则精解
2022-05-05 16:42:05
Spring MVC数据绑定方式
2023-03-18 03:06:55
Unity中的PostProcessScene实用案例深入解析
2021-06-09 04:57:28
详解三种java实现多线程的方式
2021-11-02 10:09:30
Android使用自定义View实现360手机卫士波浪球进度的效果
2023-03-21 19:18:34