如果你正在使用grant_type=“密码”, 你必须 :
在你自己的bean中创建下面的beanWebSecurityConfigurerAdapter
class
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
将其注入AuthorizationServerConfigurerAdapter
class
@Autowired
private AuthenticationManager authenticationManager;
用它在configure(AuthorizationServerEndpointsConfigurer endpoints)
method
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
endpoints.authenticationManager(authenticationManager);
}
完整示例:
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
@Override
protected UserDetailsService userDetailsService(){
InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
manager.createUser(User.withUsername("a").password("123456").authorities("USER").build());
return manager;
}
}
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
private AuthenticationManager authenticationManager;
@Autowired
public AuthorizationServerConfig(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
endpoints.authenticationManager(authenticationManager);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security) {
security.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()")
.allowFormAuthenticationForClients();
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory()
.withClient("CLIEN_ID").secret("CLIENT_SECRET")
.authorizedGrantTypes("password", "refresh_token")
.authorities("CLIENT")
.scopes("read");
}
}
Test :
curl -i -X POST -d "username=a&password=123456&grant_type=password&client_id=CLIENT_ID&client_secret=CLIENT_SECRET" http://localhost:8080/oauth/token