You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Security 6配置引发接口访问被拒及DTO反序列化问题求助

解决方案

一、修复注册接口401访问被拒问题

Spring Security 6中SecurityFilterChain是核心配置类,必须显式放行无需认证的接口。确保你的配置类包含以下规则:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            // 沙箱环境可直接关闭CSRF(POST请求默认会被CSRF拦截)
            .csrf(csrf -> csrf.disable())
            // 配置请求授权规则
            .authorizeHttpRequests(auth -> auth
                // 显式放行注册接口
                .requestMatchers("/api/v1/auth/sign_up").permitAll()
                // 其余所有请求需认证
                .anyRequest().authenticated()
            );
        return http.build();
    }
}

注意事项:

  • 若生产环境需保留CSRF,可针对性为注册接口豁免:csrf -> csrf.ignoringRequestMatchers("/api/v1/auth/sign_up")
  • 确认requestMatchers中的路径与实际接口路径完全匹配,注意大小写和前缀

二、修复RegistrationRequestDTO反序列化问题

移除Lombok排除配置后出现反序列化错误,核心原因是Jackson无法找到DTO的无参构造方法,或Lombok生成的方法不符合Jackson要求。

1. 修正DTO类的Lombok注解

在RegistrationRequestDTO上添加必要注解,确保Jackson能正常反序列化:

import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.AllArgsConstructor;

@Data
@NoArgsConstructor // 必须添加,Jackson反序列化依赖无参构造
@AllArgsConstructor // 可选,方便业务层创建实例
public class RegistrationRequestDTO {
    private String username;
    private String password;
    private String email;
    // 其他业务字段
}

2. 检查POM依赖配置

确保Lombok依赖正确引入,且版本与Spring Boot 3兼容(Spring Boot 3.0+对应Lombok 1.18.24+):

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <!-- Lombok核心依赖 -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <!-- Lombok编译期处理器(Maven编译必需) -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.18.30</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

3. 验证Jackson默认配置

Spring Boot默认已配置Jackson,若自定义了ObjectMapper,避免禁用无参构造检测:

// 请勿添加如下配置,否则会导致反序列化失败
// objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
// 若开启该配置,需确保DTO字段与请求JSON参数完全匹配

验证流程

  1. 重启应用,测试注册接口,确认不再返回401状态码
  2. 发送POST请求到/api/v1/auth/sign_up,携带匹配DTO结构的JSON参数,确认接口能正常接收并处理参数

内容的提问来源于stack exchange,提问作者Sam Fisher

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 11:10:17