Spring Boot整合新版Spring Security, 使用lambda表达式来配置,使其有更好的体验感

前言介绍

SpringSecurity是一个基于Spring开发的非常强大的权限验证框架,其核心功能包括:

  • 认证 (用户登录)
  • 授权 (此用户能够做哪些事情)
  • 攻击防护 (防止伪造身份攻击)

为什么使用lambda表达式来完成security的基本配置呢?

因为SpringSecurity 5.X版本与新版本的配置方式完全不一样,新版本全部采用lambda形式进行配置,无法再使用之前的and()方法进行连接了,所以我们使用lambda表达式完成配置

开发环境配置

我们继续使用之前的测试项目进行教学,首先我们需要导入SpringSecurity的相关依赖

xml 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

启动测试

启动,控制台没有报错,正确打印security password,即正常 验证一下,在浏览器输入地址,然后输入账号密码 成功进入 后端初始化完成

security基本配置

创建config包,并在下面创建 SecurityConfigruation 配置类

编写配置方法

放行登录,注册等校验接口,要写在conf.anyRequest().authenticated();之前,因为conf.anyRequest().authenticated();是拦截所有请求,需要进行身份验证。你放在之后,就会被拦下

这里因为我写项目的时候,使用了Jwt,所以禁用session

这里因为我返回的信息是中文,所以有乱码;设置字符集与响应格式。

处理响应乱码

处理响应乱码,使用Java自带的常量,设置字符集为UTF-8,ContentType设置成json格式。

java 复制代码
 // 处理乱码
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);

SecurityConfigruation 配置类内容

这里注释已经很详细了,我就不解释了

java 复制代码
/**
 * @author jinze
 * @version 1.0
 * @description: Security配置类
 * @date 2023/8/8 10:50
 */
@Configuration
public class SecurityConfiguration {

   @Bean
    public SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception {
        return httpSecurity
            // 配置授权规则
            .authorizeHttpRequests(conf ->{
                conf.requestMatchers("/api/auth/**").permitAll(); // 对以 /api/auth/ 开头的请求放行
                conf.anyRequest().authenticated(); // 其他请求需要身份验证
            })
            .formLogin(conf ->{
                conf.loginProcessingUrl("/api/auth/login"); // 登录请求的 URL
                conf.successHandler(this::onAuthenticationSuccess); // 登录成功处理器
                conf.failureHandler(this::onAuthenticationFailure); // 登录失败处理器
            })
            .logout(conf -> {
                conf.logoutUrl("/api/auth/logout"); // 登出请求的 URL
                conf.logoutSuccessHandler(this::onLogoutSuccess); // 登出成功处理器
            })
            .csrf(AbstractHttpConfigurer::disable) // 禁用 CSRF 保护
            .sessionManagement(conf -> conf.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) // 禁用 session
            .build();
    }

    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response,
                                        Authentication authentication) throws IOException, ServletException {
        // 处理乱码
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        //返回响应信息
        response.getWriter().write("成功");
    }
    public void onAuthenticationFailure(HttpServletRequest request,
                                        HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {
        // 处理乱码
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        //返回响应信息
        response.getWriter().write("失败");
    }

    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {

    }
相关推荐
程序员爱钓鱼9 分钟前
Go语言实战案例 — 项目实战篇:简易博客系统(支持评论)
前端·后端·go
追逐时光者7 小时前
精选 4 款基于 .NET 开源、功能强大的 Windows 系统优化工具
后端·.net
TF男孩7 小时前
ARQ:一款低成本的消息队列,实现每秒万级吞吐
后端·python·消息队列
AAA修煤气灶刘哥8 小时前
别让Redis「歪脖子」!一次搞定数据倾斜与请求倾斜的捉妖记
redis·分布式·后端
AAA修煤气灶刘哥8 小时前
后端人速藏!数据库PD建模避坑指南
数据库·后端·mysql
你的人类朋友9 小时前
什么是API签名?
前端·后端·安全
昵称为空C11 小时前
SpringBoot3 http接口调用新方式RestClient + @HttpExchange像使用Feign一样调用
spring boot·后端
架构师沉默11 小时前
设计多租户 SaaS 系统,如何做到数据隔离 & 资源配额?
java·后端·架构
RoyLin12 小时前
TypeScript设计模式:适配器模式
前端·后端·node.js
该用户已不存在12 小时前
Mojo vs Python vs Rust: 2025年搞AI,该学哪个?
后端·python·rust