解决Spring Security OAuth在访问/oauth/token时候报Bad client credentials/401 authentication is required

本文分析了Spring Security OAuth在访问/oauth/token时出现'Bad client credentials'或'401 authentication is required'错误的原因,主要是授权方式不匹配和认证问题。解决方案是在AuthenticationServerConfig中启用allowFormAuthenticationForClients,允许客户端使用表单方式授权,并添加passwordEncoder。通过这些调整,可以成功解决认证错误并获取access_token。

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

出现这个问题的具体原因一般有以下两点:

1.在授权的部分我们一般是通过使用自己的login action进行http basic的方式进行授权,而我们在使用Spring Security的时候只对外暴露了登陆的这个接口,就是说其它的接口都在Spring Security的保护范围内了,包括/oauth的接口。

2.在通过1的post方式授权通过之后使用http://localhost:8090/oauth/token?client_id=1293380307393789953&client_secret=$2a101010IYtMMj4Rc0TIX6Ty4wy/POYIydxZt.fH/p8.rWWv.pPKyIw7tFt9i&grant_type=authorization_code&code=BIX1OXu69Z&redirect_uri=http://localhost:8090/index的方式进行授权,这样是可以的,但是在接下来通过post方式向/oauth/token这个接口获取access_token的时候,会发现这个时候authentication用的并不是前面授权通过的那个authentication,而是使用的匿名登陆的那个authentication,这样前面的authentication就无法正常使用,也会因此而得到Bad client credentials/401 authentication is required。

我们可以通过如下的方式解决这个问题 ,在AuthenticationServerCo

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值