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

  先来张图片            

          

我在用psotman 测试oauth授权码模式的出现了401的异常, 就是调用oauth/token.

我是想用code换token,但是发现报错了。这是为什么呢? 首先你要理解

 

/oauth/token

  • 这个如果配置支持allowFormAuthenticationForClients的,且url中有client_id和client_secret的会走ClientCredentialsTokenEndpointFilter来保护
  • 如果没有支持allowFormAuthenticationForClients或者有支持但是url中没有client_id和client_secret的,走basic认证保护

所以我就明白怎么回事了

首先代码里面添加

 @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
        oauthServer
                .tokenKeyAccess("permitAll()")
                .checkTokenAccess("permitAll()")
                .allowFormAuthenticationForClients();
    
    //	oauthServer.allowFormAuthenticationForClients();
    }

然后再给postman 添加参数

这样就OK了

 

  • 10
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 19
    评论
Spring Security OAuth2 Authorization Server 0.3.1中,可以通过实现TokenEnhancer接口来向Access Token中添加用户信息。具体步骤如下: 1. 创建一个类,实现TokenEnhancer接口,例如: ```java public class CustomTokenEnhancer implements TokenEnhancer { @Override public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) { Map<String, Object> additionalInfo = new HashMap<>(); additionalInfo.put("user_name", authentication.getName()); ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(additionalInfo); return accessToken; } } ``` 上述代码中,我们向Access Token的附加信息中添加了一个名为"user_name"的键值对,它的值为当前用户的用户名。 2. 在Authorization Server配置类中,设置TokenEnhancer,例如: ```java @Configuration @EnableAuthorizationServer public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter { @Autowired private AuthenticationManager authenticationManager; @Autowired private UserDetailsService userDetailsService; @Autowired private DataSource dataSource; @Override public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception { endpoints.authenticationManager(authenticationManager) .userDetailsService(userDetailsService) .tokenStore(tokenStore()) .tokenEnhancer(tokenEnhancer()); } @Bean public TokenEnhancer tokenEnhancer() { return new CustomTokenEnhancer(); } // ... } ``` 在上述代码中,我们通过调用tokenEnhancer()方法来设置TokenEnhancer,它使用我们自定义的CustomTokenEnhancer类。 3. 在调用/token接口时,通过获取Access Token的响应内容,可以看到"user_name"键值对的值已经被添加到Access Token的附加信息中。 以上就是向Access Token中添加用户信息的步骤。需要注意的是,如果要添加更多的用户信息,只需要在CustomTokenEnhancer类的enhance()方法中继续向additionalInfo中添加键值对即可。
评论 19
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值