likes
comments
collection
share

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

作者站长头像
站长
· 阅读数 31

前言介绍

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

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

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

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

开发环境配置

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

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

启动测试

启动,控制台没有报错,正确打印security password,即正常 Spring Boot整合新版Spring Security, 使用lambda表达式来配置,使其有更好的体验感 验证一下,在浏览器输入地址,然后输入账号密码 Spring Boot整合新版Spring Security, 使用lambda表达式来配置,使其有更好的体验感 成功进入 Spring Boot整合新版Spring Security, 使用lambda表达式来配置,使其有更好的体验感 后端初始化完成

security基本配置

创建config包,并在下面创建 SecurityConfigruation 配置类 Spring Boot整合新版Spring Security, 使用lambda表达式来配置,使其有更好的体验感

编写配置方法

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

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

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

这里因为我返回的信息是中文,所以有乱码;设置字符集与响应格式。 Spring Boot整合新版Spring Security, 使用lambda表达式来配置,使其有更好的体验感

处理响应乱码

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

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

SecurityConfigruation 配置类内容

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


/**
 * @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 {

    }