利用Java怎么在调用接口时添加一个权限验证功能
创始人
2024-11-20 19:03:04
0次

一、编写的环境

工具:IDEA
框架:GUNS框架(自带后台权限验证配置,我们这里需要编写前端权限验证配置)

二、使用步骤

1.配置前端调用的接口

代码如下(示例):

利用Java怎么在调用接口时添加一个权限验证功能

在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.配置拦截路径

代码如下(示例):

利用Java怎么在调用接口时添加一个权限验证功能

在创建文件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;
}

相关内容

热门资讯

空调连续工作多久需要停机休息 空调连续工作的时间取决于多个因素,包括空调的型号、功率、使用环境和维护情况等。一般来说,空调可以连续...
空调哪个符号是除湿的 空调除湿功能通常用一个水滴形状的符号表示。不同品牌和型号的空调遥控器可能会有所差异,但一般来说,除湿...
格力空调多长时间加一次氟利昂 1、一般情况下,空调对氟利昂的使用量是非常小的,所以在空调使用了四年左右的时候再考虑加也没问题。2、...
空调用多长时间需要加氟一次 一般情况下是五年。当出现以下这几种情况时,空调才需要加氟。1、空调的室内机和室外机各有两个接口,当接...
格调生活·C标思享荟:卡萨帝在... 9月12日的郑州龙湖金融岛,夜风轻拂,灯光璀璨。“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑...
品牌价值破千亿、高端份额持续领... 9月12日,“C标时刻共传奇——卡萨帝思享荟暨20周年品牌盛典郑州站”在郑州龙湖金融岛举办。2026...
空调主板坏了修800还是换新的 空调主板坏了是修还是换新,需要考虑多个因素,以下是一些建议:1. 维修成本:如果维修费用较低,比如 ...
空调开多久需要休息多长时间 问题:空调开多久需要休息多长时间回答:1、在使用空调的过程中,一般空调开7~8个小时左右需要休息2~...
中央空调多长时间清洗一次 1、一般空调开机前清洗一次即可,空调开机中间时段再清洗一次,空调关机时清洗一次,这样比较合理。2、空...
中央空调氟利昂多久加一次 看空调制热和制冷程度,很多人的观点认为氟利昂必须一年放一次,其实这个观点是错误的,理解上面有点偏差,...