密码模式需要注入一个AuthenticationManager,于是咱们接着上篇授权码模式的文档的代码添加一点东西即可。
    1.配置AuthenticationManagerBean

    1. @Configuration
    2. @EnableWebSecurity
    3. public class SecurityConfig extends WebSecurityConfigurerAdapter {
    4. @Bean
    5. @Override
    6. protected AuthenticationManager authenticationManager() throws Exception {
    7. return super.authenticationManager();
    8. }
    9. @Bean
    10. @Override
    11. public UserDetailsService userDetailsService() {
    12. UserDetails user =
    13. User.builder()
    14. .username("gaoxi")
    15. .password("{noop}123456")
    16. .roles("USER")
    17. .build();
    18. return new InMemoryUserDetailsManager(user);
    19. }
    20. }

    2.注入并设置AuthenticationManager

    1. @Configuration
    2. @EnableAuthorizationServer
    3. public class AuthServerConfig implements AuthorizationServerConfigurer {
    4. @Override
    5. public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
    6. }
    7. @Override
    8. public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    9. // @formatter:off
    10. clients.inMemory().withClient("gaoxi")
    11. .secret("{noop}123456")
    12. .scopes("read","write")
    13. .authorizedGrantTypes("password","refresh_token",
    14. "authorization_code","implicit","client_credentials")
    15. .redirectUris("http://www.baidu.com");
    16. // @fomatter:on
    17. }
    18. @Resource
    19. private AuthenticationManager authenticationManager;
    20. @Override
    21. public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
    22. endpoints.authenticationManager(authenticationManager);
    23. }
    24. }

    3.Postman请求
    localhost:8080/oauth/token?grant_type=password&username=gaoxi&password=123456 注意Authorization中内容。
    image.png