Java的接口调用时的权限验证功能的实现

 更新时间:2020年11月26日 11:09  点击:1738

提示:这里可以添加本文要记录的大概内容:

例如:一般系统前端调用后台相关功能接口时,需要验证此时用户的权限是否满足调用该接口的条件,因此我们需要配置相应的验证权限的功能。

提示:以下是本篇文章正文内容,下面案例可供参考

一、编写的环境

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

二、使用步骤

1.配置前端调用的接口

代码如下(示例):

在WebSecurityConfig文件中配置

在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

在创建文件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框架本来自带接口权限验证功能,只不过只是针对后台而已,我在这里添加了针对前端的权限验证,仅供参考。

到此这篇关于Java的接口调用时的权限验证功能的实现的文章就介绍到这了,更多相关Java 接口调用时权限验证内容请搜索猪先飞以前的文章或继续浏览下面的相关文章希望大家以后多多支持猪先飞!

[!--infotagslink--]

相关文章