spring-boot - GET 和 POST 的不同身份验证
问题描述
我一直在关注一个弹簧安全示例,但我无法理解它。一个简单的 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 的 CSRF 保护在 Spring Security 中默认启用。POST
请求受此行为影响。
通过执行以下操作禁用它:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
}
推荐阅读
- angular - 在模板驱动表单中禁用 mat-form-field
- r - 使用 R 中的过滤器函数过滤具有多个变量的多个条件
- python - 使用 .join() 将列表值转换为在 python 中面临错误的字符串
- discord - Discord:通过 ID 获取频道返回 undefined / null
- c++ - 在类的 qlist 中搜索字符串
- flutter - 溢出属性不会剪辑文本小部件中的内容
- json - 如何在python中将字节转换为json
- javascript - 如何制作一个可以决定使用传递的数据运行哪个函数的程序?
- amazon-web-services - 要合并 www 和非 www,我应该使用 Route 53 中的 A 记录还是两个 CloudFront 分配?
- c# - 如何通过向其发送 pdf 文件 c# 来使用 api-rest 服务