如何解决Spring Boot Post请求移动端403禁止访问错误
Hey there! It's totally normal to hit this roadblock when you're new to Spring Boot REST development—Postman works smoothly, but mobile clients throw a 403. Let's walk through the most common fixes to get your POST requests working across all clients:
1. Fix Cross-Origin Resource Sharing (CORS) Restrictions
Postman doesn't enforce CORS rules like mobile browsers or apps do. If your mobile app is hosted on a different domain/port than your backend, you need to explicitly allow cross-origin requests.
Per-controller quick fix: Add the
@CrossOriginannotation to your REST controller (or specific methods) to test with open access:@RestController @CrossOrigin(origins = "*") // Adjust this to your mobile app's actual domain in production public class YourApiController { // Your POST endpoint logic here }Global CORS configuration: For a scalable solution that applies to all endpoints, create a global config class:
@Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") // Replace with your mobile app's origin for production .allowedMethods("GET", "POST", "PUT", "DELETE") .allowedHeaders("*"); } }
2. Check Spring Security CSRF Protection
Spring Security enables CSRF protection by default, which blocks POST requests that don't include a valid CSRF token. Postman might be bypassing this (either because you haven't set up security yet, or you manually added the token), but your mobile app isn't handling it.
Temporary test: Disable CSRF: If you're not using authentication yet, disable CSRF to confirm this is the issue (never do this in production!):
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .authorizeRequests() .anyRequest().permitAll(); } }Production-ready CSRF handling: If you need CSRF protection, your mobile app should:
- Send a GET request first to fetch the
XSRF-TOKENcookie that Spring sets. - Include the token in the
X-XSRF-TOKENheader of your POST request.
- Send a GET request first to fetch the
3. Verify Request Headers and Payload
Double-check that your mobile app is sending identical headers and payload to what you use in Postman:
- Make sure the
Content-Typeheader is set toapplication/json(if you're sending JSON data). - Confirm the request body has no formatting errors or missing fields compared to your working Postman request.
- Check for any authentication tokens or custom headers that Postman includes but your mobile app is missing.
内容的提问来源于stack exchange,提问作者Harshal Deshmukh

