环境 JDK11, SpringBoot 2.2.2.RELEASE
相关依赖坐标:
implementation'org.springframework.boot:spring-boot-starter-aop'implementation'io.jsonwebtoken:jjwt:0.9.0'
1.自定义权限认证注解
importjava.lang.annotation.*; /*** 角色权限校验注解*/ElementType.METHOD}) ({RetentionPolicy.RUNTIME) (public@interfaceHasRoles { String[] roles() default""; }
2、Aop前置通知切面类
importcom.example.dynamicdatatable.domain.SysAccountInfo; importcom.example.dynamicdatatable.enums.AccountType; importcom.example.dynamicdatatable.repository.SysAccountMapper; importlombok.extern.slf4j.Slf4j; importorg.aspectj.lang.annotation.Aspect; importorg.aspectj.lang.annotation.Before; importorg.aspectj.lang.annotation.Pointcut; importorg.springframework.stereotype.Component; importorg.springframework.util.ObjectUtils; importjavax.annotation.Resource; importjavax.servlet.http.HttpServletRequest; importjava.util.HashSet; importjava.util.Set; /*** 权限认证切面类*/publicclassCheckRoleAop { value="@annotation(HasRoles)") (publicvoidpointCut() {}; privateSysAccountMapperaccountMapper; privateHttpServletRequestrequest; /*** todo 身份认证和权限比对* @param hasRoles 权限认证注解入参*/value="pointCut()&&@annotation(hasRoles)") (publicvoidexec(HasRoleshasRoles) { // jwt解密认证// ...// jwt解密认证结束longid=10; // 模拟解析Token后 取得的id值AccountTypeaccountType=AccountType.ADMIN_TYPE; // 模拟解析Token后, 取得的用户账户类别// 每次请求都动态实时的去查询用户信息和权限信息SysAccountInfoaccountInfo=accountMapper.findById(id, accountType); if (ObjectUtils.isEmpty(accountInfo) ||!accountInfo.isEnableState() ||accountInfo.isDelState()) { log.error("用户不存在"); thrownewRuntimeException("用户不存在"); } else { // 模拟从数据库中查询账户拥有的角色身份权限Set<String>rolesToken=newHashSet<String>(1) { privatestaticfinallongserialVersionUID=-1307833886578391108L; { add("admin"); } }; String[] roles=hasRoles.roles(); if (roles.length==0) { return; } else { for (Stringrole : roles) { if (rolesToken.contains(role)) { // 将解析后的Token信息实体缓存到请求域中JwtSessionCacheEntityjwtSessionCacheEntity=newJwtSessionCacheEntity(); jwtSessionCacheEntity.setId(id); jwtSessionCacheEntity.setAccountType(accountType); jwtSessionCacheEntity.setRoleCode("admin"); request.setAttribute("info", jwtSessionCacheEntity); return; } } } log.warn("用户无对应的权限"); thrownewRuntimeException("无权限"); } } }
3、请求域缓存实体类
importlombok.Data; importjava.io.Serializable; /*** Jwt 请求域缓存数据实体*/publicclassJwtSessionCacheEntityimplementsSerializable { privatestaticfinallongserialVersionUID=-4634413454684601681L; privateLongid; privateStringroleCode; privateAccountTypeaccountType; }
4、账户类型枚举类
importlombok.AllArgsConstructor; importlombok.Getter; /*** 账户类型枚举类*/publicenumAccountType { ACCOUNT_TYPE(1, "sys_account_info"), ADMIN_TYPE(2, "sys_admin_info"), ; privateintcode; privateStringtableName; }