Spring boot中如何在POST请求中获得授权而不是出现401未授权访问?

问题描述 投票:0回答:1

我的所有

GET
请求在授权访问下都可以正常工作,但是,我所有
POST
请求都以 401 未经授权的访问返回,并且我正在使用用户名和密码进行基本授权,我猜问题是从 CSRF 令牌中出现的,但我已禁用但什么也没发生。

下面是我的

SecurityConfig
课程

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                //.cors(Customizer.withDefaults())
                .csrf((csrf) -> csrf.disable())
                .authorizeHttpRequests((authz) -> authz
                        .requestMatchers(HttpMethod.GET, "/api/**").permitAll()
                        //.requestMatchers(HttpMethod.POST, "/api/**").permitAll()
                        .anyRequest().authenticated()
                )
                .httpBasic(Customizer.withDefaults());

        return http.build();

    }

    @Bean
    public UserDetailsService users() {
        // The builder will ensure the passwords are encoded before saving in memory
        //User.UserBuilder users = User.withDefaultPasswordEncoder();
        UserDetails user = User.builder()
                .username("user")
                .password(passwordEncoder().encode("pass"))
                .roles("USER")
                .build();
        UserDetails admin = User.builder()
                .username("admin")
                .password(passwordEncoder().encode("admin"))
                .roles("USER", "ADMIN")
                .build();
        return new InMemoryUserDetailsManager(user, admin);
    }


}

这是我的控制器

    @PreAuthorize("hasRole(ADMIN)")
    @PostMapping
    public ResponseEntity<PostDto> createPost(@Valid @RequestBody PostDto postDto) {
        return new ResponseEntity<>(postService.createPost(postDto), HttpStatus.CREATED);
    }

这些是我的日志

2023-09-10T23:55:35.850+02:00 DEBUG 20476 --- [nio-8080-exec-7] o.s.security.web.csrf.CsrfFilter         : Invalid CSRF token found for http://localhost:8080/api/posts
2023-09-10T23:55:35.850+02:00 DEBUG 20476 --- [nio-8080-exec-7] o.s.s.w.access.AccessDeniedHandlerImpl   : Responding with 403 status code
2023-09-10T23:55:35.851+02:00 DEBUG 20476 --- [nio-8080-exec-7] o.s.security.web.FilterChainProxy        : Securing POST /error
2023-09-10T23:55:35.851+02:00 DEBUG 20476 --- [nio-8080-exec-7] o.s.s.w.a.AnonymousAuthenticationFilter  : Set SecurityContextHolder to anonymous SecurityContext
2023-09-10T23:55:35.852+02:00 DEBUG 20476 --- [nio-8080-exec-7] s.w.a.DelegatingAuthenticationEntryPoint : Trying to match using And [Not [RequestHeaderRequestMatcher [expectedHeaderName=X-Requested-With, expectedHeaderValue=XMLHttpRequest]], MediaTypeRequestMatcher [contentNegotiationStrategy=org.springframework.web.accept.ContentNegotiationManager@379dbd63, matchingMediaTypes=[application/xhtml+xml, image/*, text/html, text/plain], useEquals=false, ignoredMediaTypes=[*/*]]]
2023-09-10T23:55:35.852+02:00 DEBUG 20476 --- [nio-8080-exec-7] s.w.a.DelegatingAuthenticationEntryPoint : Trying to match using Or [RequestHeaderRequestMatcher [expectedHeaderName=X-Requested-With, expectedHeaderValue=XMLHttpRequest], And [Not [MediaTypeRequestMatcher [contentNegotiationStrategy=org.springframework.web.accept.ContentNegotiationManager@379dbd63, matchingMediaTypes=[text/html], useEquals=false, ignoredMediaTypes=[]]], MediaTypeRequestMatcher [contentNegotiationStrategy=org.springframework.web.accept.ContentNegotiationManager@379dbd63, matchingMediaTypes=[application/atom+xml, application/x-www-form-urlencoded, application/json, application/octet-stream, application/xml, multipart/form-data, text/xml], useEquals=false, ignoredMediaTypes=[*/*]]], MediaTypeRequestMatcher [contentNegotiationStrategy=org.springframework.web.accept.ContentNegotiationManager@379dbd63, matchingMediaTypes=[*/*], useEquals=true, ignoredMediaTypes=[]]]
2023-09-10T23:55:35.852+02:00 DEBUG 20476 --- [nio-8080-exec-7] s.w.a.DelegatingAuthenticationEntryPoint : Match found! Executing org.springframework.security.web.authentication.DelegatingAuthenticationEntryPoint@7ca4ed9f
2023-09-10T23:55:35.852+02:00 DEBUG 20476 --- [nio-8080-exec-7] s.w.a.DelegatingAuthenticationEntryPoint : Trying to match using RequestHeaderRequestMatcher [expectedHeaderName=X-Requested-With, expectedHeaderValue=XMLHttpRequest]
2023-09-10T23:55:35.853+02:00 DEBUG 20476 --- [nio-8080-exec-7] s.w.a.DelegatingAuthenticationEntryPoint : No match found. Using default entry point org.springframework.security.web.authentication.www.BasicAuthenticationEntryPoint@74626aab

Spring启动v3.1.2

如果有人可以提供帮助,我将不胜感激。

spring-boot post authorization csrf-token spring-boot-security
1个回答
0
投票

仅在配置类中定义方法是不够的。 Spring security 有一个默认的安全过滤器链,如果你想覆盖某些行为,你必须提供自己的 bean。

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) { ... }

@Bean
注释是必要的,因为您想要传达“在这里,使用此方法创建一个SecurityFilterChain bean”。一旦 Bean 出现在上下文中,它就会被自动拾取。

回答你的问题“我应该将它添加到 Spring boot 中的每个方法中还是什么?”:
不,你不应该。当您想要指定您的方法返回一个由 spring 上下文管理的 bean 时,您可以添加它。通常您会使用此方法配置 spring 的某些方面,但通常您的方法不会返回 beans。

© www.soinside.com 2019 - 2024. All rights reserved.