利用Java怎么在调用接口时添加一个权限验证功能?相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。
一、编写的环境
工具: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;
}
看完上述内容,你们掌握利用Java怎么在调用接口时添加一个权限验证功能的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。