java - Spring 安全登录404

标签 java spring spring-boot spring-security

我正在探索 Spring 的一些东西。 我遇到了 Spring Boot 的简单端点,请参阅:

@Controller
@EnableAutoConfiguration
public class SampleController {

    @RequestMapping("/sample")
    @ResponseBody
    String sample() {
        return "Hello sample!";
    }

    @RequestMapping("/sample2")
    @ResponseBody
    String sample2() {
        return "Hello sample secured!";
    }
}

逻辑上可以在 localhost:8181/sample 上访问端点

但是在使用 spring security 时,“ protected ”端点变得无法访问,因为登录页面给了我 404

login page gives me 404

我的安全级别如下:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/sample" ).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);
    }
}

我能够访问/sample,因为它不 protected 。但无法访问 /sample2,因为它重定向到 /login

我根据本指南配置我的安全级别:https://spring.io/guides/gs/securing-web/

最佳答案

I am able to access /sample as is not protected. But unable to access /sample2 as it redirects to /login

因为您在安全配置中没有绕过 /sample2

 .antMatchers("/sample2" ).permitAll()

另一件事是,正如您指定的自定义登录页面

.formLogin()
.loginPage("/login")

您必须提供登录页面。

关于java - Spring 安全登录404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50054993/

相关文章:

java - 为图像拖动动画

java - Eclipse 中的包资源管理器 View

JAVA Mail 和 Office 365 在连接时挂起

Javafx 在对象更改时更新 TableView

java - Jersey 将空值序列化为 json : How to skip

java - Spring Boot JSP 配置不起作用

spring - H2 SQL语法异常

java - 使用 Apache Kafka 进行实时消息传递

java - CRUDRepository findAll 发现空

java - 如何为 spring-boot 应用程序设置 logging.path?