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

在搭建SpringCloudOAuth2项目时遇到访问/oauth/token返回invalid_client错误的问题。问题源于AuthorizationServerConfigurerAdapter配置中client的secret未使用加密。解决方案是引入PasswordEncoder,使用BCryptPasswordEncoder对密码进行加密处理。在WebSecurityConfigurerAdapter中定义并注入PasswordEncoder,然后在配置client时使用encoder.encode()方法加密secret。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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();
	}
}
/oauth/check_token 接口通常用于OAuth 2.0验证过程中,客户端向授权服务器发送访问令牌以验证其有效性。要在这个接口上自定义认证,你需要做以下几个步骤: 1. **设置路由**:首先,在你的后端服务中配置相应的路由处理程序,将`/oauth/check_token`映射到你的API控制器或模块。 ```python # 使用Flask示例 from flask import Flask, request app = Flask(__name__) @app.route('/oauth/check_token', methods=['POST']) def check_token(): # 这里是你的认证逻辑 ``` 2. **解析请求数据**:从HTTP POST请求中获取access_token或者其他必要的验证信息。 ```python token_data = request.get_json() access_token = token_data.get('access_token') ``` 3. **验证逻辑**:检查access_token是否有效,这通常涉及到查询数据库、API提供商的验证服务,或者使用JWT(JSON Web Tokens)库解码并验证签发者和过期时间。 4. **响应结果**:如果验证成功,返回确认信息;失败则返回错误状态码和消息。 ```python if validate_access_token(access_token): return {'status': 'success', 'message': 'Token is valid'} else: return {'status': 'error', 'message': 'Invalid or expired token'}, 401 ``` 5. **错误处理和日志**:确保捕获和记录可能出现的异常,并提供友好的错误信息给客户端。 注意,具体的实现细节会依赖于你使用的框架(如Django、Express.js等)以及后端语言(Python、Node.js等)。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值