1

I configured the password mode in spring security oauth2, but when I send request, the postman shows error:

invaild_client, description: Bad client credentials.

Here's my configuration.

Postman request screenshot: click here

AuthenicationServerConfig:


@Configuration
@EnableAuthorizationServer
public class AuthenicationServerConfig extends AuthorizationServerConfigurerAdapter {
    @Autowired
    private ClientDetailsService clientDetailsService;
    @Autowired
    private TokenStore tokenStore;
    @Autowired
    public DataSource dataSource;
    @Autowired
    public AuthenticationManager authenticationManager;
    @Autowired
   public PasswordEncoder encoder;
    //Authentication
    @Bean
    public ClientDetailsService clientDetailsService(){
        return new InMemoryClientDetailsService();
    }
    @Bean
    public AuthorizationServerTokenServices tokenService(){
        DefaultTokenServices defaultTokenServices=new DefaultTokenServices();
        defaultTokenServices.setTokenStore(tokenStore);
        defaultTokenServices.setReuseRefreshToken(true);
        defaultTokenServices.setClientDetailsService(clientDetailsService);
        defaultTokenServices.setRefreshTokenValiditySeconds(259200);
        defaultTokenServices.setAccessTokenValiditySeconds(3600*24);
        return defaultTokenServices;
            }
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
       clients  .inMemory()
                .withClient("user1")
                .secret(encoder.encode("999999999"))//密钥
                .resourceIds("resource1")
                .scopes("all")//资源列表
                .authorizedGrantTypes("authentication_code","password","client_credentials","implicit","refresh_token")//允许的授权类型
                .autoApprove(false);//跳转到授权页面

    }
    @Bean
    public BCryptPasswordEncoder encoder(){
        BCryptPasswordEncoder passwordEncoder=new BCryptPasswordEncoder();
        return passwordEncoder;
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security
                .tokenKeyAccess("permitAll()")//oauth/token_key公开
                .checkTokenAccess("permitAll()").allowFormAuthenticationForClients();//oauth/checktoken公开
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints
                .authenticationManager(authenticationManager)
             .tokenStore(tokenStore).allowedTokenEndpointRequestMethods(HttpMethod.POST,HttpMethod.GET);
    }
}

SecurityConfig:


@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    public DataSource dataSource;
    @Autowired
    public PasswordEncoder encoder;

    @Bean
    public AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests().anyRequest().permitAll();
        http.csrf().disable();
    }

    @Override
    protected UserDetailsService userDetailsService() {
        return new MyUserDetailsService();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService());
    }
}

I made my own implementation on MyUserDetailsService:


@Service
public class MyUserDetailsService implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<User> wrapper=new QueryWrapper<>();
        wrapper.eq("username",username);
        User user=userMapper.selectOne(wrapper);
        if(user==null)
            throw new UsernameNotFoundException("用户名未找到!");
        List<GrantedAuthority> grantedAuthorityList=new ArrayList<>();
        grantedAuthorityList.add(new SimpleGrantedAuthority("ROLE_administrator"));
        grantedAuthorityList.add(new SimpleGrantedAuthority("ROLE_guest"));
        return new MyUserPrincipal(user.getUsername(),user.getPassword(),grantedAuthorityList);
    }
}

MyUserPrincipal:


public class MyUserPrincipal implements UserDetails {
    public String username;
    public String password;
    public List<GrantedAuthority> grantedAuthorityList;
    public MyUserPrincipal(String username, String password,List<GrantedAuthority> grantedAuthorityList) {
        this.username = username;
        this.password = password;
        this.grantedAuthorityList=grantedAuthorityList;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return grantedAuthorityList;
    }

    @Override
    public String getPassword() {
        return password;
    }

    @Override
    public String getUsername() {
        return username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }
}
skobaljic
  • 9,379
  • 1
  • 25
  • 51
a1557944
  • 11
  • 3

0 Answers0