问题出处
在访问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认证授权”系列文章。