Spring Security OAuth2.0申请令牌访问/oauth/token时候报401 authentication is required

本文解决在使用Spring Security OAuth2.0的密码模式认证时,访问/oauth/token断点申请令牌出现401authenticationisrequired错误的问题。通过在认证服务配置类中配置allowFormAuthenticationForClients,使表单认证生效。

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

问题出处

在访问Spring Security OAuth2.0提供的/oauth/token断点申请令牌报401 authentication is required错误。
具体场景如下:
1、使用OAuth2.0的密码模式认证
2、问题图片如下:
在这里插入图片描述

解决问题

在/oauth/token 的请求中我们指定了client_id和client_secret,所以会走ClientCredentialsTokenEndpointFilter,此时需要我们配置支持allowFormAuthenticationForClients。
在认证服务配置类中进行配置:

@Configuration
@EnableAuthorizationServer
public class AuthorizationServer extends AuthorizationServerConfigurerAdapter {
...
...
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security){
        security
                .tokenKeyAccess("permitAll()")                    //oauth/token_key是公开
                .checkTokenAccess("permitAll()")                  //oauth/check_token公开
                .allowFormAuthenticationForClients()				//表单认证(申请令牌)
        ;
    }

}

重启认证服务,再次测试,一切正常了
在这里插入图片描述
如果解决了你的问题就请点个赞。

详细代码参考:https://github.com/pbteach/SpringSecurity/blob/master/distributed-security/distributed-security-uaa/src/main/java/com/pbteach/security/distributed/uaa/config/AuthorizationServer.java
同时也请关注 “跟着燕青学Spring Security认证授权”系列文章。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值