使用MVC+Java调用Facebook API发帖遇OAuth回调404错误求助
Hey there, sorry to hear you've been stuck on this 404 issue for three days—let's break this down step by step. Based on what you described, the problem hits right after Facebook redirects back to your callback URL, so let's go through the most common culprits tied to your setup:
First, double-check if your callback path /oauth2callback/Facebook is correctly mapped to your controller in web.xml, and confirm your app's context path matches MyUrl:
- Ensure your servlet mapping covers the full callback path. For example:
<servlet> <servlet-name>OAuthCallbackServlet</servlet-name> <servlet-class>com.yourpackage.FacebookCallbackServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>OAuthCallbackServlet</servlet-name> <url-pattern>/MyUrl/oauth2callback/*</url-pattern> </servlet-mapping> - Pay attention to case sensitivity! If your mapping uses lowercase
facebookbut the redirect URL usesFacebook, it'll trigger a 404. - Confirm your app's context path is indeed set to
/MyUrl(check for<context-param>inweb.xmlor server deployment settings if you're using Tomcat/Jetty).
If you're using a framework like Spring MVC or JAX-RS, make sure your callback method is bound to the exact path:
- For Spring MVC:
@Controller public class FacebookOAuthController { @GetMapping("/MyUrl/oauth2callback/Facebook") public String handleFacebookCallback(@RequestParam("code") String authCode) { // Process auth code logic here return "redirect:/post-share-success"; } } - For JAX-RS:
@Path("/MyUrl/oauth2callback") public class OAuthResource { @GET @Path("/Facebook") public Response handleCallback(@QueryParam("code") String authCode) { // Handle authorization flow return Response.seeOther(URI.create("/post-share-success")).build(); } } - Also, check if any security filters (like Spring Security) are blocking the callback path—add it to your allowed/whitelisted paths if needed.
Head to your Facebook App Dashboard, navigate to Facebook Login > Settings, and verify the Valid OAuth Redirect URIs field matches your exact callback URL:
- It should look something like:
http://your-domain.com/MyUrl/oauth2callback/Facebook(match HTTP/HTTPS, domain, context path, and callback path exactly). - A common mistake here is omitting the
MyUrlcontext path or using the wrong protocol (e.g., HTTPS for a local HTTP server).
Pull up your app server's access logs (e.g., Tomcat's localhost_access_log.*.txt). Look for the request from Facebook—it will show the full URL the server received. For example:
127.0.0.1 - - [15/Oct/2024:14:35:00 +0800] "GET /MyUrl/oauth2callback/Facebook?code=abc123XYZ HTTP/1.1" 404 1234
This will confirm if the incoming path matches your mapped routes, or if there's a discrepancy in context path, casing, or trailing slashes.
If you can share snippets of your actual web.xml mapping, controller code, or Facebook console redirect URI setup, we can narrow this down even further!
内容的提问来源于stack exchange,提问作者rayo329

