资讯专栏INFORMATION COLUMN

spring boot 利用注解实现权限验证

keelii / 1325人阅读

摘要:这里使用来实现权限验证引入依赖定义注解后台登录授权权限验证的注解此注解只能修饰方法当前注解如何去保持拦截实现登录和权限验证登录验证登录验证验证判断是否进行权限验证从切面中获取当前方法得到了方提取出他的注解进行权限验证权限验证为最高

这里使用 aop 来实现权限验证
引入依赖

    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/vu...

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/72376.html

相关文章

  • 使用JWT保护你的Spring Boot应用 - Spring Security实战

    摘要:创建应用有很多方法去创建项目,官方也推荐用在线项目创建工具可以方便选择你要用的组件,命令行工具当然也可以。对于开发人员最大的好处在于可以对应用进行自动配置。 使用JWT保护你的Spring Boot应用 - Spring Security实战 作者 freewolf 原创文章转载请标明出处 关键词 Spring Boot、OAuth 2.0、JWT、Spring Security、SS...

    wemall 评论0 收藏0
  • spring boot 基于外部权限系统扩展Session Repository实现登陆权限验证

    摘要:在进行一些公司内部系统开发中,经常会需要对接公司内部统一的权限管理系统进行权限角色验证等等。在实际开发过程中可以借助的实现权限验证功能。 在进行一些公司内部系统开发中,经常会需要对接公司内部统一的权限管理系统进行权限角色验证等等。在实际开发过程中可以借助Spring的Session Repository实现权限验证功能。实现步骤如下: 一、添加自定义Session注解EnableUse...

    thekingisalwaysluc 评论0 收藏0
  • Spring Boot实践——三种拦截器的创建

    摘要:中的拦截器在开发中,拦截器是经常用到的功能。该拦截器只能过滤请求,允许多个拦截器同时存在,通过拦截器链管理。当时不再执行后续的拦截器链及被拦截的请求。实现拦截器大致也分为两种,一种是实现接口,另一种利用的注解或配置。 Spring中的拦截器   在web开发中,拦截器是经常用到的功能。它可以帮我们验证是否登陆、权限认证、数据校验、预先设置数据以及统计方法的执行效率等等。今天就来详细的谈...

    fnngj 评论0 收藏0
  • Spring Boot [集成-Shiro]

    摘要:后面的文章将围绕着集成来进行展开。表示当前已经身份验证或者通过记住我登录的。表示当前需要角色和。参考资料系列十五安全框架一基本功能权限管理学习资料使用手册跟开涛学博客版跟开涛学版官方文档 导读: 在阅读这篇文章之前假设你已经对Apache Shiro(后面统一用Shiro作为代指)有了一定的了解,如果你还对Shiro不熟悉的话在这篇文章的结尾附有相关的学习资料,关于Shiro是用来做什...

    gclove 评论0 收藏0
  • Spring Boot [集成-Shiro]

    摘要:后面的文章将围绕着集成来进行展开。表示当前已经身份验证或者通过记住我登录的。表示当前需要角色和。参考资料系列十五安全框架一基本功能权限管理学习资料使用手册跟开涛学博客版跟开涛学版官方文档 导读: 在阅读这篇文章之前假设你已经对Apache Shiro(后面统一用Shiro作为代指)有了一定的了解,如果你还对Shiro不熟悉的话在这篇文章的结尾附有相关的学习资料,关于Shiro是用来做什...

    superw 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<