Spring Security OAuth2 SSO登录后出现401未授权问题求助
Hey there! Let's troubleshoot that 401 error you're facing after Facebook login. I've gone through your code and configuration, and here are the key issues and fixes to get your SSO working properly:
1. Fix Facebook Developer Platform Callback URL
First, the most common pitfall: your Facebook app's redirect URI isn't set correctly. Spring Boot 2.x OAuth2 clients use a default callback path for Facebook: http://localhost:8080/login/oauth2/code/facebook.
- Go to your Facebook Developer Dashboard → Your App → Products → Facebook Login → Settings
- Add the above URI to the Valid OAuth Redirect URIs list. Without this, Facebook can't send the authorization code back to your app, so Spring never creates an authenticated session, leading to the 401 when accessing
/user.
2. Update OAuth2 Configuration to Spring Boot 2.x Standards
Your current application.yml uses the old Spring Security OAuth (legacy) configuration format. Spring Boot 2.1+ uses Spring Security 5's OAuth2 client model, which is more robust and aligns with modern standards. Replace your security config with this:
spring: security: oauth2: client: registration: facebook: client-id: 233668646673605 client-secret: 33b17e044ee6a4fa383f46ec6e28ea1d scope: - email - public_profile # Ensures we get the user's name provider: facebook: authorization-uri: https://www.facebook.com/dialog/oauth token-uri: https://graph.facebook.com/oauth/access_token user-info-uri: https://graph.facebook.com/me?fields=id,name,email # Explicitly request name field user-name-attribute: id
This removes unnecessary legacy settings like tokenName and authenticationScheme, and ensures we request the right user fields from Facebook.
3. Fix the /user Endpoint for OAuth2User
Your current endpoint returns a Principal, but the structure doesn't match what your frontend expects. Instead, use @AuthenticationPrincipal to directly get the OAuth2User object and return a simple map with the user's name:
@SpringBootApplication @EnableOAuth2Sso @RestController public class SocialApplication extends WebSecurityConfigurerAdapter { // Updated /user endpoint @RequestMapping("/user") public Map<String, Object> user(@AuthenticationPrincipal OAuth2User oauth2User) { return Collections.singletonMap("name", oauth2User.getAttribute("name")); } @Override protected void configure(HttpSecurity httpSec) throws Exception{ httpSec .antMatcher("/**") .authorizeRequests() .antMatchers("/", "/login**", "/webjars/**", "/error**") .permitAll() .anyRequest() .authenticated() .and().logout().logoutSuccessUrl("/").permitAll() .and().csrf().csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()); } public static void main(String[] args) { SpringApplication.run(SocialApplication.class, args); } }
4. Fix Frontend JavaScript Issues
Your JS has two critical problems:
- Invalid selector:
$("\.unauthenticated")uses unnecessary escaping (the backslash breaks the selector) - Missing CSRF token in the AJAX request (required since you enabled CSRF protection)
Update your index.html script section to this:
<script type="text/javascript"> $(function() { // Get CSRF token from cookie (you're using js-cookie, which is already included) var csrfToken = Cookies.get('XSRF-TOKEN'); $.ajax({ url: "/user", headers: { "X-XSRF-TOKEN": csrfToken }, success: function(data) { $("#user").html(data.name); $(".unauthenticated").hide(); $(".authenticated").show(); }, error: function(xhr) { // If 401, show login link if (xhr.status === 401) { $(".unauthenticated").show(); $(".authenticated").hide(); } } }); }); </script>
Why This Works
- The Facebook redirect URI fix ensures the authorization code flows correctly, creating an authenticated session in Spring.
- The updated OAuth2 config uses Spring Security 5's native client support, which handles Facebook's OAuth flow properly.
- The
/userendpoint returns a clean JSON structure that your frontend can easily parse. - The fixed JS selector and CSRF token ensure the AJAX request is allowed and the UI updates as expected.
Give these changes a try, and you should see the user's name displayed after logging in with Facebook!
内容的提问来源于stack exchange,提问作者AfamO

