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 {

    }
相关推荐
过期动态11 小时前
Java开发中的@EnableWebMvc注解和WebMvcConfigurer接口
java·开发语言·spring boot·spring·tomcat·maven·idea
野犬寒鸦12 小时前
从零起步学习并发编程 || 第一章:初步认识进程与线程
java·服务器·后端·学习
我爱娃哈哈12 小时前
SpringBoot + Flowable + 自定义节点:可视化工作流引擎,支持请假、报销、审批全场景
java·spring boot·后端
韩师学子--小倪12 小时前
SpringBoot 优雅停服
spring boot·tomcat
李梨同学丶14 小时前
0201好虫子周刊
后端
思想在飞肢体在追14 小时前
Springboot项目配置Nacos
java·spring boot·后端·nacos
JavaGuide16 小时前
推荐一个基于 Spring Boot 4.0 + Java 21 + Spring AI 2.0 的大模型项目!
java·spring boot·spring
Loo国昌16 小时前
【垂类模型数据工程】第四阶段:高性能 Embedding 实战:从双编码器架构到 InfoNCE 损失函数详解
人工智能·后端·深度学习·自然语言处理·架构·transformer·embedding
小马爱打代码17 小时前
Spring Boot :使用 Spring Cache 注解方式集成 Redis
spring boot·redis·spring
ONE_PUNCH_Ge17 小时前
Go 语言泛型
开发语言·后端·golang