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

本文探讨了在使用OAuth和Spring Security集成时遇到的问题,即通过授权后获取access_token时出现401错误的情况。文章提供了详细的解决方案,通过在配置中允许客户端使用表单方式进行认证。

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

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

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

2.在通过1的post方式授权通过之后使用/oauth/authorize?grant_type=password&username=user&password=pwd&client_id=app&response_type=code&redirect_uri=http://localhost的方式进行授权,这样是可以的,但是在接下来通过post方式向/oauth/token这个接口获取access_token的时候,会发现这个时候authentication用的并不是前面授权通过的那个authentication,而是使用的匿名登陆的那个authentication,这样前面的authentication就无法正常使用,也会因此而得到401 authentication is required。


我们可以通过如下的方式解决这个问题 ,在AuthenticationServerConfig这个配置中,启用AuthenticationServerSecurityConfiguration的allowFormAuthenticationForClients允许client使用form的方式进行authentication的授权,具体可以参考如下代码:

@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
    //enable client to get the authenticated when using the /oauth/token to get a access token
    //there is a 401 authentication is required if it doesn't allow form authentication for clients when access /oauth/token
    oauthServer.allowFormAuthenticationForClients();
}



评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值