首页 > 解决方案 > 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-bootspring-securityspring-security-rest

解决方案


Spring 的 CSRF 保护在 Spring Security 中默认启用。POST请求受此行为影响。

通过执行以下操作禁用它:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();
}

推荐阅读