即使csrf被禁用,Spring引导也会为Mobile请求抛出403



我有一个简单的Spring启动应用程序,它有一个POST rest api方法来注册用户。当我通过Postman测试它时,这非常有效。但当我从我的移动应用程序测试它时,它总是抛出403。这在选项级别失败,因为我看不到我的后端记录了一个尝试的请求。

这个问题的常见解决方案是在spring安全配置中禁用csrf。有趣的是,我有这个残疾人,但仍然得到403分。我已经尽可能多地搜索了,但找不到解决方案,说明这仍然失败。感谢任何人提供的帮助。

这是安全配置。

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
// Some beans that are not relevant
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/register").permitAll()
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and().exceptionHandling().accessDeniedHandler(accessDeniedHandler)
.and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
}
}

我认为还值得一提的是,我还在许多其他线程中尝试添加cors禁用选项,但没有成功。

@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable()
.authorizeRequests()
.antMatchers("/register").permitAll()
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and().exceptionHandling().accessDeniedHandler(accessDeniedHandler)
.and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
}

这就是我的控制器看起来像的样子

@RestController
public class AuthenticationResource {
// Wiring and other methods
@RequestMapping(value = "/register", method = RequestMethod.POST)
public ResponseEntity<?> registerNewUser(@Valid @RequestBody UserRegistrationRequest request) {
if (!request.getConfirmPassword().equals(request.getPassword())) {
throw new MyException(ErrorUtil.generateErrorFieldsValue("password", "confirmPassword"),
"Passwords do not match!", HttpStatus.BAD_REQUEST);
}
UserAccountResponse savedUserAccount = userAccountService.save(request);
return ResponseEntity.ok(savedUserAccount);
}
}

如果需要其他详细信息,请告诉我。

据我所知,正如您所建议的,这与CORS有关,但通过使用http.cors(),您可以告诉spring查找一个名为corsFilter()的bean。在我的其他项目中,这就是我解决问题的方法。

@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource configSource = new 
UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
// GET , POST, HEAD
config.applyPermitDefaultValues();
config.addAllowedMethod(HttpMethod.PUT);
config.addAllowedMethod(HttpMethod.DELETE);
config.addAllowedMethod(HttpMethod.OPTIONS);
configSource.registerCorsConfiguration("/**", config);
return new CorsFilter(configSource);
}

最新更新