Spring boot - 不允许 POST 方法

bes*_*art 11 java rest spring spring-security

我正在解决这个问题...我有一个带有 S2S 通信的 Spring Boot 应用程序。我有一个@RestController应该接受 POST 请求的方法。

这是控制器

@RestController
public class PaymentRestController {

@PostMapping("/util/paymentResponse")
    public void savePaymentResponse(@RequestParam boolean transaction_status, @RequestParam String usedToken,
            @RequestParam String transaction_message, @RequestParam String authCode,
            @RequestParam String transactionCode, @RequestParam String orderId, HttpServletRequest request) {
//business logic
}

}
Run Code Online (Sandbox Code Playgroud)

如果我点击此链接,我会收到 405 错误,方法不允许

第一次我发现请求被 Web 应用程序上启用的 CSFR 过滤器阻止,所以我以这种方式配置了我的安全性

@Configuration
@ComponentScan("it.besmart")
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter{

    @Autowired
    @Qualifier("customUserDetailsService")
    UserDetailsService userDetailsService;

    @Autowired
    CustomSuccessHandler customSuccessHandler;

    @Autowired
    CustomAuthenticationFailureHandler customAuthenticationFailureHandler;

    @Autowired
    DataSource dataSource;

    private final static Logger logger = LoggerFactory.getLogger(SecurityConfiguration.class);

    @Autowired
    public void configureGlobalService(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());

    }

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

    @Bean
    public SwitchUserFilter switchUserFilter() {
        SwitchUserFilter filter = new SwitchUserFilter();
        filter.setUserDetailsService(userDetailsService);
        filter.setSuccessHandler(customSuccessHandler);
        filter.setFailureHandler(customAuthenticationFailureHandler);
        return filter;
    }

        protected void configure(HttpSecurity http) throws Exception {
            logger.debug("Webapp security configured");


            http

            .authorizeRequests()
                    .antMatchers("/",  "/home", "/contacts", "/faq", "/privacy", "/register", "/registrationConfirm", "/util/**", "/resendRegistrationToken","/park**", "/oauth/authorize", "/error")
                    .permitAll()
                    .antMatchers("/profile**", "/edit**","/payment**", "/plate**","/notification**", "/addPaymentMethod**", "/logout/impersonate**")
                    .access("hasRole('USER') or hasRole('NOPAYMENT')")
                    .antMatchers("/book**", "/manage**")
                    .access("hasRole('USER')")
                    .antMatchers("/admin**", "/login/impersonate**").access("hasRole('ADMIN')")
                    .antMatchers("/updatePassword").hasAuthority("CHANGE_PASSWORD_PRIVILEGE")

                    .and().formLogin().loginPage("/?login=login").loginProcessingUrl("/")                   .successHandler(customSuccessHandler).failureHandler(customAuthenticationFailureHandler).usernameParameter("email").passwordParameter("password").and().rememberMe().rememberMeParameter("remember-me").tokenRepository(persistentTokenRepository()).tokenValiditySeconds(86400).and().exceptionHandling().accessDeniedPage("/accessDenied")

                    .and().csrf().ignoringAntMatchers( "/util**")
                    .and().logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                    .logoutSuccessUrl("/?logout=true").permitAll()


                    .and().addFilterAfter(switchUserFilter(), FilterSecurityInterceptor.class);

        }
Run Code Online (Sandbox Code Playgroud)

通过这种方式,我没有收到 CSRF 令牌异常,但仍然收到 405 错误。这甚至不是 POST 的问题,因为如果我更改为 GET 请求和映射,我仍然会收到 405 错误...如果我尝试发送 POST,我会在标头响应中看到允许的方法是 POST,如果我用 GET 发送它,我会看到允许的方法 POST...奇怪

我不知道在哪里可以看到...

8bi*_*tme 11

在我的例子中,端点有 ssl,即https

在邮递员中我错误地使用了http

httpGET对于s可以正常工作,但对于POSTs 它会返回 405 不允许的方法。https如果您的端点期望如此,它就必须如此。

如果您在 Spring 中打开了请求和响应日志记录,则POST上述情况下的端点将记录如下:

[2021-02-26T10:40:07+02:00] (my-app/fffffa343226e) 2021-02-26T08:40:07,915Z (UTC+0) [http-nio-80-exec-6] DEBUG o.s.w.f.CommonsRequestLoggingFilter - Before request [GET /api/v1/my-app, client=1.2.3.4, user=aUser]
[2021-02-26T10:40:07+02:00] (my-app/fffffa343226e) 2021-02-26T08:40:07,915Z (UTC+0) [http-nio-80-exec-6] WARN  o.s.w.s.m.s.DefaultHandlerExceptionResolver - Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported]
[2021-02-26T10:40:07+02:00] (my-app/fffffa343226e) 2021-02-26T08:40:07,916Z (UTC+0) [http-nio-80-exec-6] DEBUG o.s.w.f.CommonsRequestLoggingFilter - After request [GET /api/v1/my-app, client=1.2.3.4, user=aUser]

Run Code Online (Sandbox Code Playgroud)


mar*_*rco 5

所以问题是其中一个参数为空。已解决在请求参数注释处添加 required=null ,如下所示:

@RequestParam(value = "yourParamName", required = false)
Run Code Online (Sandbox Code Playgroud)

这会导致 405,如下定义:

6.5.5.  405 Method Not Allowed

The 405 (Method Not Allowed) status code indicates that the method
received in the request-line is known by the origin server but not
supported by the target resource.  The origin server MUST generate an
Allow header field in a 405 response containing a list of the target
resource's currently supported methods.

A 405 response is cacheable by default; i.e., unless otherwise
indicated by the method definition or explicit cache controls (see
Section 4.2.2 of [RFC7234]).
Run Code Online (Sandbox Code Playgroud)

当此处定义“目标资源”时