我正在探索 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
我的安全级别如下:
@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/