spring - 存在 WebSecurityConfig 时出现 404
问题描述
spring-boot-starter-parent 2.4.1
spring-boot-starter-安全
package ru.pcask.securing.config;
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.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
@Bean
@Override
public UserDetailsService userDetailsService() {
UserDetails user =
User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.roles("USER")
.build();
return new InMemoryUserDetailsManager(user);
}
}
这是从官方教程(https://spring.io/guides/gs/securing-web/)中复制的。
问题:
当我注释掉他的配置文件中的每一行时,它会显示一个 Spring 安全登录页面。开箱即用的登录表单,使用 Bootstrap 制作。
但是当我取消注释这段代码并被重定向到 http://localhost:8080/login 时,会出现这个错误:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Wed Dec 30 19:50:40 MSK 2020
There was an unexpected error (type=Not Found, status=404).
接下来我可以尝试什么来解决这个问题?
解决方案
问题出在这行代码中,您希望对每个请求进行身份验证。
anyRequest().authenticated()
如果您想将某些链接或所有链接列入白名单,您可以显式添加它们,这在上述调用之前添加非常重要
.anyMatchers("/**").permitAll() // whitelists all
.anyMatchers("/pages/**").permitAll() // whitelists /pages/...
.anyRequest().authenticated()
推荐阅读
- php - 如何链接到页面的特定部分 HTML PHP
- c# - 当后端代码中的简单键值变量工作相同时,为什么要使用 redis 作为缓存层?
- google-apps-script - Google Slides Apps 脚本检索页面中的形状
- python-3.x - 在 KNeighborsClassifier 中使用自定义指标时,我不断收到“TypeError:只有整数标量数组可以转换为标量索引”
- java - JavaFX - 在使用选项卡时将 GUI 拆分为单独的类
- jquery - 通过函数调整电子窗口大小
- scheme - 匹配方案中的括号
- android - 当我使用 adb 显示 /sys/kernel/debug/tracing/available_filter_functions 时没有这样的设备
- python - 初始化以迭代抽象pyomo模型中的集合?
- angular-cli - 运行 ng serve -o 时出现错误