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 分钟前
高效使用AI从了解 Prompt / Agent / MCP 开始
前端·人工智能·后端
Maxkim12 分钟前
🐳 前端工程师的后端小实验:Docker + Sequelize 玩转 MySQL API 🚀
javascript·后端
mao毛44 分钟前
Go 1.25 重磅发布:性能飞跃、工具升级与新一代 GC 来袭
后端·go
我是场1 小时前
Android14内核调试 - boot & vendor_boot
java·开发语言·spring boot
Harold1 小时前
【用户访问鉴权】Openresty实现方案
后端
用户9704438781161 小时前
PHP 函数的参数顺序,它们是随机的吗?
后端·程序员·代码规范
3学习分享吧1 小时前
C++从0实现百万并发Reactor服务器(完结)
后端
lssjzmn1 小时前
java中,synchronized 关键字与 ReentrantLock 重入锁的区别以及应用场景,注意事项
java·后端
南雨北斗1 小时前
词性
后端
南雨北斗1 小时前
动词的类型
后端