基于Spring Boot 3 + Spring Security6 + JWT + Redis实现接口资源鉴权

本文详细描述了如何在SpringBoot3项目中集成SpringSecurity6、JWT和Redis,包括修改UserDetailsService获取用户权限、实现认证和鉴权异常处理程序,以及如何在Security配置中添加方法安全授权和异常统一处理。通过示例展示了如何在API中应用权限控制和测试鉴权过程。
摘要由CSDN通过智能技术生成

紧接上一篇文章,基于Spring Boot 3 + Spring Security6 + JWT + Redis实现接口资源鉴权

系列文章指路👉
系列文章-基于SpringBoot3创建项目并配置常用的工具和一些常用的类

项目源码👉
/shijizhe/boot-test

1. 修改 UserDetailsService

采用RBCA模型进行权限控制.

简化后我们有三个表: 用户表、用户角色关联表、角色权限关联表(表结构源码中有:src/main/resources/static/数据结构.sql)

修改取用户的权限列表

     <select id="listAuthorityById" resultType="java.lang.String">
          SELECT pe.permission_id
          FROM ya_user_role ro,
               ya_role_permission pe
          WHERE ro.role_id = pe.role_id
          AND ro.user_id = #{userId}
     </select>

将权限列表放入UserDetail中

在这里插入图片描述

2. 新增认证和鉴权异常统一处理程序

做这一步的目的是:程序遇到未知的错误,仍可以返回json形式的错误信息,可以帮助排查问题。

实现AuthenticationEntryPoint

/**
 * <p>
 *  认证异常处理
 * </p>
 *
 * @author Ya Shi
 * @since 2024/3/28 16:01
 */
@Component
@Slf4j
public class YaAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        log.error("YaAuthenticationEntryPoint commence 认证过程中遇到异常:{}", authException.toString());
        ServletUtils.renderResult(response, new BaseResult<>(ResultEnum.FAILED_UNAUTHORIZED.code, "Security auth failed."));
    }
}

实现AccessDeniedHandler

/**
 * <p>
 * 鉴权异常处理
 * </p>
 *
 * @author Ya Shi
 * @since 2024/3/28 16:06
 */
@Component
@Slf4j
public class YaAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        log.error("YaAccessDeniedHandler handle 鉴权过程中遇到异常:{}", accessDeniedException.toString());
        ServletUtils.renderResult(response, new BaseResult<>(ResultEnum.FAILED_FORBIDDEN.code, "鉴权失败:" + accessDeniedException.getMessage()));
    }
}

修改Security配置 YaSecurityConfig.securityFilterChain

  1. 允许方法安全授权
@EnableMethodSecurity
  1. securityFilterChain新增异常统一处理
 .exceptionHandling()
      .authenticationEntryPoint(authenticationEntryPoint)
      .accessDeniedHandler(accessDeniedHandler)
      .and()

剩余重复代码就不贴了,上篇文章有。
在这里插入图片描述
在这里插入图片描述

简单测试

给方法加权限控制

@PreAuthorize("hasAuthority('ya_fruit_list')")
    @GetMapping("/testApi")
    @Operation(summary = "testApi", description = "测试使用-直接返回成功")
    @PreAuthorize("hasAuthority('ya_fruit_list')")
    public Object testApi(){
        String userId = UserAuthUtils.getUserId();
        System.out.println(userId);
        return BaseResult.success(userId);
    }

调用测试(事先已登录)

在这里插入图片描述
请求一个没有权限的接口:

    @GetMapping("/testApi2")
    @Operation(summary = "testApi2", description = "测试使用2-直接返回成功")
    @PreAuthorize("hasAuthority('test_test_123456')")
    public Object testApi2(){
        String userId = UserAuthUtils.getUserId();
        System.out.println(userId);
        return BaseResult.success(userId);
    }

在这里插入图片描述

  • 25
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
基于SpringBoot2、MyBatisPlus、Spring Security5.7、JWTRedis的开发框架可以提供以下功能和优势: 1. Spring Boot2是一个轻量级的Java开发框架,能够快速构建Web应用程序和微服务。它提供了自动配置和约定大于配置的设计理念,减少了开发的复杂性。 2. MyBatisPlus是一个在MyBatis基础上进行扩展的ORM框架,提供了更简洁、更便捷的数据库访问方式。它支持代码生成、自动SQL映射、分页查询等功能,能够进一步提高开发效率。 3. Spring Security5.7是一个基于Spring的身份认证和授权框架,可以进行用户认证、角色授权、API权限控制等。它提供了一套完整的解决方案,保护应用程序免受各种安全威胁。 4. JWT(Json Web Token)是一种用于跨网络进行身份验证的开放标准。它使用JSON对象作为令牌,可以在客户端和服务器之间传递信息。JWT具有无状态、可扩展、跨平台等特点,适用于分布式系统和移动应用程序。 5. Redis是一种高性能的键值存储系统,它支持数据持久化、集群模式、发布订阅等功能。在开发过程中,可以使用Redis存储JWT令牌、缓存数据等,提高系统的性能和可扩展性。 综上所述,基于SpringBoot2、MyBatisPlus、Spring Security5.7、JWTRedis的开发框架具有快速开发、高效数据库访问、可靠的安全保护和可扩展的分布式支持等优势。它可以帮助开发者快速构建稳定、安全、高性能的Web应用程序和微服务。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小雅痞

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值