Spring Boot 1.5.12整合Spring Security OAuth2获取令牌报错求助
Hey there! Let's tackle this access token issue you're hitting while integrating Spring Security with OAuth2 on Spring Boot 1.5.12.RELEASE. From the logs you shared, I can see Hibernate is correctly querying the user table for the requested username, but the TokenEndpoint log cuts off—so let's walk through the most common causes and fixes for this scenario.
Common Causes & Fixes
1. Incomplete UserDetails Implementation
Spring Security OAuth2 relies heavily on the UserDetails interface to validate user credentials and permissions. If your custom user entity doesn't properly implement this interface, or your UserDetailsService isn't mapping user data correctly to a valid UserDetails object, token generation will fail silently or throw an uncaught exception.
Fix:
Either implement UserDetails directly on your User entity, or create a dedicated UserDetailsService implementation that converts your entity to Spring's built-in User object. Here's a working example:
@Service public class CustomUserDetailsService implements UserDetailsService { @Autowired private UserRepository userRepository; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User appUser = userRepository.findByUsername(username); if (appUser == null) { throw new UsernameNotFoundException("User not found with username: " + username); } // Map your app user to Spring Security's UserDetails return org.springframework.security.core.userdetails.User.withUsername(appUser.getUsername()) .password(appUser.getPassword()) .authorities(Collections.singleton(new SimpleGrantedAuthority(appUser.getRole().getName()))) .accountExpired(false) .accountLocked(false) .credentialsExpired(false) .disabled(false) .build(); } }
2. Password Encoding Misconfiguration
Spring Boot 1.5.x doesn't auto-configure a password encoder for OAuth2, so if your stored passwords aren't encrypted with a matching encoder (or you haven't specified the encoder in your security config), authentication will fail, preventing token issuance.
Fix:
Add a password encoder bean to your security config, and ensure it's used both for storing passwords and authenticating users:
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private CustomUserDetailsService userDetailsService; @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService) .passwordEncoder(passwordEncoder()); } // Expose AuthenticationManager for OAuth2 @Override @Bean public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } }
Note: Make sure any passwords stored in your database are encrypted using BCryptPasswordEncoder (not plain text)!
3. Invalid OAuth2 Authorization/Client Configuration
Misconfigurations in your authorization server or client details are another frequent culprit. Common issues include incorrect client IDs/secrets, missing grant types, or misconfigured endpoint permissions.
Fix:
Verify your AuthorizationServerConfigurerAdapter implementation has valid client settings and correctly uses the authentication manager:
@Configuration @EnableAuthorizationServer public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { @Autowired private AuthenticationManager authenticationManager; @Autowired private PasswordEncoder passwordEncoder; @Override public void configure(ClientDetailsServiceConfigurer clients) throws Exception { clients.inMemory() .withClient("your-client-id") .secret(passwordEncoder.encode("your-client-secret")) .authorizedGrantTypes("password", "refresh_token") .scopes("read", "write") .accessTokenValiditySeconds(3600); } @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints.authenticationManager(authenticationManager); } }
Also, double-check your token request parameters: send a POST to /oauth/token with form data including grant_type=password, username=your-username, password=your-password, client_id=your-client-id, and client_secret=your-client-secret.
4. Missing or Incomplete Dependencies
Ensure you have all required OAuth2 dependencies in your build file. For Maven:
<dependency> <groupId>org.springframework.security.oauth</groupId> <artifactId>spring-security-oauth2</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
For Gradle:
compile 'org.springframework.security.oauth:spring-security-oauth2' compile 'org.springframework.boot:spring-boot-starter-security'
Next Steps
If none of these fixes work, share the full TokenEndpoint log (the part that got cut off) and any relevant exception stack traces. Also, include snippets of your UserDetailsService, security config, and authorization server config—this will help pinpoint the exact issue.
内容的提问来源于stack exchange,提问作者Vishal Parashar

