Spring Boot - 不允许使用 POST 方法 [英] Spring boot - POST method not allowed
问题描述
我一直在解决这个问题...我有一个具有 S2S 通信功能的 Spring Boot 应用程序.我有一个 @RestController
方法,它应该接受 POST 请求.
I'm dwelling with this problem... I have a Spring Boot application wit a S2S communication. I have a @RestController
method which should accept POST request.
这是控制器
@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
}
}
如果我点击此链接,我会收到 405 错误,方法不允许
If i hit this link i get a 405 error, method not allowed
我第一次发现请求被 Web 应用程序上启用的 CSFR 过滤器阻止,所以我以这种方式配置了我的安全
At first time i found that the request was blocked by the CSFR Filter which is enabled on the web application, so I have configured my security in this way
@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);
}
通过这种方式,我没有收到 CSRF 令牌异常,但仍然收到 405 错误.这甚至不是 POST 的问题,因为如果我更改为 GET 请求和映射,我仍然会收到 405 错误...如果我尝试发送 POST,我会在标头响应中看到 Allowed 方法是 POST,如果我在 GET 中发送它,我会看到允许的方法 POST...很奇怪
In this way i'm not getting the CSRF token exception, but still getting the 405 error. It's not even a problem of POST because if i change to GET the request and the mapping, i still take the 405 error... And if i try to send a POST, i see in the header response that the Allowed method is POST, if i send it in GET i see allowed method POST... weird
我不知道在哪里可以看到...
I don't know where to see...
推荐答案
所以问题是其中一个参数为空.已解决在请求参数注解处添加required=null,如下:
So the problem was that one of the parameter was null. It has been solved adding required=null at the request parameter annotation, like that:
@RequestParam(value = "yourParamName", required = false)
这会导致 405,定义如下:
this cause a 405, as defined here:
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]).
这篇关于Spring Boot - 不允许使用 POST 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!