Spring Cloud OAuth2中访问/oauth/token报invalid_client问题的解决

Spring Cloud OAuth2中访问/oauth/token报invalid_client问题的解决

问题分析

初建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();
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值