首页 > 解决方案 > 存在 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).

接下来我可以尝试什么来解决这个问题?

标签: springspring-bootspring-security

解决方案


问题出在这行代码中,您希望对每个请求进行身份验证。

anyRequest().authenticated()

如果您想将某些链接或所有链接列入白名单,您可以显式添加它们,这在上述调用之前添加非常重要

.anyMatchers("/**").permitAll() // whitelists all 
.anyMatchers("/pages/**").permitAll() // whitelists /pages/...

.anyRequest().authenticated()

推荐阅读