【发布时间】:2023-01-11 17:56:38
【问题描述】:
我正在使用 Spring Boot 3、Spring Security 6。我的安全配置无法正常工作。我有 2 条路径,在这些路径上应该允许任何请求,而对于其他所有内容,都需要进行身份验证。
GET 和 POST 方法都适用于需要身份验证的方法。
在具有 permitAll() 的那些上,只有 GET 请求有效。对于 POST,我得到 401 Unauthorised。
我处理了 csrf,无论如何我希望所有 POST 请求都能正常工作,而不仅仅是那些具有身份验证的请求。
在 Postman 上,我选择了 POST、No Auth、放入 RAW 正文并选择了 JSON。我真的不知道为什么它不起作用。
这是我的代码:
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http, KeycloakLogoutHandler keycloakLogoutHandler) throws Exception {
http.authorizeHttpRequests().requestMatchers("/firstpath/**", "/secondpath/**").permitAll().and()
.authorizeHttpRequests().anyRequest().authenticated().and()
.oauth2ResourceServer(oauth2 -> oauth2.jwt());
http.oauth2Login()
.and()
.logout()
.addLogoutHandler(keycloakLogoutHandler)
.logoutSuccessUrl("/");
http.csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse());
return http.build();
}
}
@Slf4j
@RestController
@RequestMapping("/firstpath")
public class NameitController {
@PostMapping(value = "path", produces = WSConstants.JSON_MEDIATYPE)
@ResponseBody
public ResponseEntity saveMyObject(@RequestBody ObjectDTO dto) {
[...] //my code
}
}
我也试过http.authorizeHttpRequests().requestMatchers(HttpMethod.POST,"/firstpath/path").permitAll(),但没有用。
编辑:它仍然与 csrf 保护有关,因为当我累了 http.csrf().disable(); 时,一切正常。但我仍然想要 csrf 保护,好像令牌不是用 permitAll() 发送的?...
【问题讨论】:
标签: spring-boot spring-security