springboot利用注解实现权限验证的实现代码

这里使用 aop 来实现权限验证

创新互联是专业的德保网站建设公司,德保接单;提供成都网站设计、成都网站建设,网页设计,网站设计,建网站,PHP网站建设等专业做网站服务;采用PHP框架,可快速的进行德保网站开发网页制作和功能扩展;专业做搜索引擎喜爱的网站,专业的做网站团队,希望更多企业前来合作!

引入依赖


  org.springframework.boot
  spring-boot-starter-aop

定义注解

package com.lmxdawn.api.admin.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * 后台登录授权/权限验证的注解
 */
//此注解只能修饰方法
@Target(ElementType.METHOD)
//当前注解如何去保持
@Retention(RetentionPolicy.RUNTIME)
public @interface AuthRuleAnnotation {
  String value();
}

拦截实现登录和权限验证

package com.lmxdawn.api.admin.aspect;

import com.lmxdawn.api.admin.annotation.AuthRuleAnnotation;
import com.lmxdawn.api.admin.enums.ResultEnum;
import com.lmxdawn.api.admin.exception.JsonException;
import com.lmxdawn.api.admin.service.auth.AuthLoginService;
import com.lmxdawn.api.common.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.List;

/**
 * 登录验证 AOP
 */
@Aspect
@Component
@Slf4j
public class AuthorizeAspect {

  @Resource
  private AuthLoginService authLoginService;

  @Pointcut("@annotation(com.lmxdawn.api.admin.annotation.AuthRuleAnnotation)")
  public void adminLoginVerify() {
  }

  /**
   * 登录验证
   *
   * @param joinPoint
   */
  @Before("adminLoginVerify()")
  public void doAdminAuthVerify(JoinPoint joinPoint) {

    ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
    if (attributes == null) {
      throw new JsonException(ResultEnum.NOT_NETWORK);
    }
    HttpServletRequest request = attributes.getRequest();

    String id = request.getHeader("X-Adminid");

    Long adminId = Long.valueOf(id);

    String token = request.getHeader("X-Token");
    if (token == null) {
      throw new JsonException(ResultEnum.LOGIN_VERIFY_FALL);
    }

    // 验证 token
    Claims claims = JwtUtils.parse(token);
    if (claims == null) {
      throw new JsonException(ResultEnum.LOGIN_VERIFY_FALL);
    }
    Long jwtAdminId = Long.valueOf(claims.get("admin_id").toString());
    if (adminId.compareTo(jwtAdminId) != 0) {
      throw new JsonException(ResultEnum.LOGIN_VERIFY_FALL);
    }

    // 判断是否进行权限验证
    MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    //从切面中获取当前方法
    Method method = signature.getMethod();
    //得到了方,提取出他的注解
    AuthRuleAnnotation action = method.getAnnotation(AuthRuleAnnotation.class);
    // 进行权限验证
    authRuleVerify(action.value(), adminId);
  }

  /**
   * 权限验证
   *
   * @param authRule
   */
  private void authRuleVerify(String authRule, Long adminId) {

    if (authRule != null && authRule.length() > 0) {

      List authRules = authLoginService.listRuleByAdminId(adminId);
      // admin 为最高权限
      for (String item : authRules) {
        if (item.equals("admin") || item.equals(authRule)) {
          return;
        }
      }
      throw new JsonException(ResultEnum.AUTH_FAILED);
    }

  }

}

Controller 中使用

使用 AuthRuleAnnotation 注解, value 值就是在数据库里面定义的 权限规则名称

/**
 * 获取管理员列表
 */
@AuthRuleAnnotation("admin/auth/admin/index")
@GetMapping("/admin/auth/admin/index")
public ResultVO index(@Valid AuthAdminQueryForm authAdminQueryForm,
           BindingResult bindingResult) {

  if (bindingResult.hasErrors()) {
    return ResultVOUtils.error(ResultEnum.PARAM_VERIFY_FALL, bindingResult.getFieldError().getDefaultMessage());
  }

  if (authAdminQueryForm.getRoleId() != null) {
    List authRoleAdmins = authRoleAdminService.listByRoleId(authAdminQueryForm.getRoleId());
    List ids = new ArrayList<>();
    if (authRoleAdmins != null && !authRoleAdmins.isEmpty()) {
      ids = authRoleAdmins.stream().map(AuthRoleAdmin::getAdminId).collect(Collectors.toList());
    }
    authAdminQueryForm.setIds(ids);
  }
  List authAdminList = authAdminService.listAdminPage(authAdminQueryForm);

  // 查询所有的权限
  List adminIds = authAdminList.stream().map(AuthAdmin::getId).collect(Collectors.toList());
  List authRoleAdminList = authRoleAdminService.listByAdminIdIn(adminIds);

  // 视图列表
  List authAdminVoList = authAdminList.stream().map(item -> {
    AuthAdminVo authAdminVo = new AuthAdminVo();
    BeanUtils.copyProperties(item, authAdminVo);
    List roles = authRoleAdminList.stream()
        .filter(authRoleAdmin -> authAdminVo.getId().equals(authRoleAdmin.getAdminId()))
        .map(AuthRoleAdmin::getRoleId)
        .collect(Collectors.toList());
    authAdminVo.setRoles(roles);
    return authAdminVo;
  }).collect(Collectors.toList());

  PageInfo authAdminPageInfo = new PageInfo<>(authAdminList);
  PageSimpleVO authAdminPageSimpleVO = new PageSimpleVO<>();
  authAdminPageSimpleVO.setTotal(authAdminPageInfo.getTotal());
  authAdminPageSimpleVO.setList(authAdminVoList);

  return ResultVOUtils.success(authAdminPageSimpleVO);

}

相关地址

GitHub 地址: https://github.com/lmxdawn/vue-admin-java

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持创新互联。


当前题目:springboot利用注解实现权限验证的实现代码
文章出自:http://pwwzsj.com/article/ijjeeh.html