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 {

    }
相关推荐
陈随易1 分钟前
Kimi k2不行?一个小技巧,大幅提高一次成型的概率
前端·后端·程序员
Victor35617 分钟前
MySQL(133)如何解决MySQL连接超时问题?
后端
亚洲第一中锋_哈达迪17 分钟前
详解缓存淘汰策略:LRU
后端·缓存·golang
婪苏18 分钟前
Python 数据类型详解:从基础到拷贝机制
后端
icecreamstorm20 分钟前
MySQL索引
后端·mysql
-dzk-23 分钟前
【Flask】基础入门
后端·python·pycharm·django·flask·conda·pip
盖世英雄酱5813626 分钟前
同事的代码问题第六期(MQ与多线程处理数据)
后端
import_random26 分钟前
[python]PATH环境变量(优先级)
后端
寻月隐君1 小时前
用 Rust 实现 HTTPie:一个现代 CLI 工具的构建过程
后端·rust·github
LaoZhangAI2 小时前
Browser MCP完全指南:5分钟掌握AI浏览器自动化新范式(2025最新)
前端·后端