问题分析
初建Spring Cloud OAuth2项目中访问获取access_token票证的端点/oauth/token时报invalid_client错误,postman中错误信息如下:
{
"error": "invalid_client",
"error_description": "Bad client credentials"
}
如下图:
Java后台警告如下:
2021-01-16 18:14:53.482 WARN 11764 --- [nio-5002-exec-2] o.s.s.c.bcrypt.BCryptPasswordEncoder : Encoded password does not look like BCrypt
导致以上问题的原因是在最新Spring Cloud Security OAuth2中,在AuthorizationServerConfigurerAdapters实现类中定义client设置secret时必须要使用密码加密,而不能直接使用明文密码。
问题解决
关键代码
把以下代码
package com.wongoing.oauth2.config;
@Configuration
@EnableAuthorizationServer
public class OAuth2ServerConfig extends AuthorizationServerConfigurerAdapter {
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory().withClient("client_1").secret("123456")
.authorizedGrantTypes("password")
.scopes("all");
}
}
改为如下的代码方式
package com.wongoing.oauth2.config;
@Configuration
@EnableAuthorizationServer
public class OAuth2ServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
private PasswordEncoder passwordEncoder;
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory().withClient("client_1").secret(this.passwordEncoder.encode("123456"))
.authorizedGrantTypes("password")
.scopes("all");
}
}
在WebSecurityConfigurerAdapter实现类中定义PasswordEncoder。
package com.wongoing.oauth2.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}