我有一个简单的 Spring Boot 应用程序,它有一个 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);
}
}
如果需要任何其他详细信息,请告诉我。
答案 0 :(得分:-1)
据我所知,这与您建议的 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);
}