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

Spring Security:requestMatchers无法放行根路径/的问题求助

问题描述

我跟着旧教程实现Spring Security,配置类里的antMatchers方法不被识别,查资料知道requestMatchers是替代方案,但根路径/还是需要认证才能访问,想放行这个路径。

我的控制器代码:

package com.quadri.springsecurity.controllers;

import java.util.Arrays;
import java.util.List;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.quadri.springsecurity.models.Student;

@RestController
@RequestMapping("api/v1/students")
public class StudentController {

    private static final List<Student> STUDENTS = Arrays.asList(
        new Student(1, "James Bond"),
        new Student(2, "Maria Jones"),
        new Student(3, "Anna Smith")
    );

    @GetMapping(path = "{studentId}")
    public Student getStudent(@PathVariable("studentId") Integer studentId) {
        return STUDENTS.stream()
        .filter(student -> studentId.equals(student.getStudentId()))
        .findFirst()
        .orElseThrow(() -> new IllegalStateException("Student " + studentId + " does not exist!"));
    }
}

安全配置类代码:

package com.quadri.springsecurity.security;

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.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class ApplicationSecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests()
                .requestMatchers( "resources/**", "/").permitAll()
                .anyRequest().authenticated()
                .and()
            .httpBasic();
        
        return http.build();
    }
}

我在resources/static下创建了index.html用来显示hello world,教程里用的是.antMatcher但我用的版本不支持,POM文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>3.0.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.quadri</groupId>
    <artifactId>spring-security</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>spring-security</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

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

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

请问确保首页或/ URL被放行的正确方法是什么?


解决方案

你的问题源于Spring Security 6.x(对应Spring Boot 3.x)的匹配规则变化,以及静态资源的默认映射逻辑,调整配置即可解决:

  1. 修正requestMatchers的路径匹配规则
    Spring Boot会自动将resources/static下的文件映射到根路径,无需加resources前缀。你需要明确放行根路径、首页文件以及静态资源目录:

    .requestMatchers("/", "/index.html", "/static/**").permitAll()
    

    也可以用AntPathRequestMatcher构建更严谨的匹配规则:

    import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
    
    // ...
    .requestMatchers(
        AntPathRequestMatcher.antMatcher("/"),
        AntPathRequestMatcher.antMatcher("/static/**")
    ).permitAll()
    
  2. 完整的安全配置类
    调整后的配置类如下,建议在简单HTTP Basic认证场景下关闭CSRF,避免额外拦截:

    package com.quadri.springsecurity.security;
    
    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.config.annotation.web.configuration.EnableWebSecurity;
    import org.springframework.security.web.SecurityFilterChain;
    
    @Configuration
    @EnableWebSecurity
    public class ApplicationSecurityConfig {
    
        @Bean
        public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
            http
                .csrf(csrf -> csrf.disable())
                .authorizeHttpRequests(auth -> auth
                    .requestMatchers("/", "/index.html", "/static/**").permitAll()
                    .anyRequest().authenticated()
                )
                .httpBasic();
            
            return http.build();
        }
    }
    
  3. 原配置不生效的原因

    • 原配置中的"resources/**"是错误路径,访问静态资源时不需要加resources前缀;
    • Spring Security的规则顺序很重要,permitAll的规则必须放在anyRequest().authenticated()之前,否则会被全局认证规则覆盖。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 17:16:08