已定义URL访问规则,Spring Security仍要求输入用户名和密码
Spring Security Basic Auth 静态资源访问仍需认证问题
我配置了Spring Security Basic Auth的URL访问规则,期望直接访问resources/static目录下的index.html,但系统仍弹出用户名和密码输入框。
我使用的配置代码
@Configuration @EnableWebSecurity public class ApplicationSecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests( (authz) -> authz .requestMatchers("/", "index", "/css/*", "/js/*").permitAll() .anyRequest() .authenticated()) .httpBasic(withDefaults()); return http.build(); } }
项目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.1.0</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>demo</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-starter-security</artifactId> <version>3.1.0</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
问题原因及解决方案
问题出在URL匹配规则的两个细节上:
- 路径缺少斜杠:
requestMatchers中的"index"没有前缀斜杠,Spring Security无法匹配实际访问路径/index; - 资源路径匹配范围不足:
/css/*和/js/*只能匹配一级子路径,无法匹配css或js目录下的子文件夹资源,需要改用/**匹配所有子层级。
修正后的配置代码:
@Configuration @EnableWebSecurity public class ApplicationSecurityConfig { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(authz -> authz .requestMatchers("/", "/index", "/css/**", "/js/**").permitAll() .anyRequest().authenticated()) .httpBasic(withDefaults()); return http.build(); } }
补充说明:Spring Boot默认会将resources/static下的index.html映射到根路径/,配置/的规则可直接访问首页;如果通过/index路径访问,则必须显式配置/index的允许规则。
内容的提问来源于stack exchange,提问作者simplenick
相关产品推荐
相关产品推荐

