【发布时间】:2021-11-10 00:46:50
【问题描述】:
我一直在关注一个弹簧安全示例,但我无法理解它。一个简单的 RestController 在 GetMapping("/hello") 上用 200 状态码回复你好。将其更改为 PostMapping 后,我会收到一个 401,用于发送相同的凭据。
似乎我在这里遗漏了一些基本的东西,因为我希望两个请求都返回 200 状态代码。
安全配置:
@Configuration
public class ProjectConfig extends WebSecurityConfigurerAdapter {
@Override
@Bean
public UserDetailsService userDetailsService() {
return new InMemoryUserDetailsManager(
List.of(
User.withUsername("john")
.password("12345")
.authorities("ROLE_ADMIN")
.build(),
User.withUsername("jane")
.password("12345")
.authorities("ROLE_MANAGER")
.build()
)
);
}
@Bean
public PasswordEncoder passwordEncoder() {
return NoOpPasswordEncoder.getInstance();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.httpBasic()
.and()
.authorizeRequests()
.anyRequest()
.hasRole("ADMIN");
}
}
具有以下 get 映射的 RestController 对此调用返回 200:
curl -v -u john:12345 localhost:8080/hello
还有这个映射:
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello!";
}
}
具有以下后映射的 RestController 对此调用返回 401:
curl -X POST -v -u john:12345 localhost:8080/hello
还有这个映射:
@RestController
public class HelloController {
@PostMapping("/hello")
public String hello() {
return "Hello!";
}
}
【问题讨论】:
标签: spring-boot spring-security spring-security-rest