【发布时间】:2021-06-28 12:33:05
【问题描述】:
我有一个简单的 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);
}
}
如果需要任何其他详细信息,请告诉我。
【问题讨论】:
-
app和postman使用的url是一样的吗?
-
将
org.springframework.security: DEBUG添加到您的日志中,看看 Spring Security 告诉您什么消息。
标签: java spring spring-boot spring-security csrf