springBoot集成oAuth2,系列六(如何获取refresh_token)

1,423 阅读1分钟

系列文章:

SpringBoot 集成 OAuth2 系列一(最简单配置篇)

SpringBoot 集成 OAuth2 系列二(password篇)

springBoot集成oAuth2,系列三(UserDetailsService篇)

springBoot集成oAuth2,系列四(前后端分离web页面中使用oauth2跨域问题篇)

springBoot集成oAuth2,系列五(下载等location.href 如何使用token)

springBoot集成oAuth2,系列六(如何获取refresh_token)

springBoot集成oAuth2,系列七(根据refresh_token获取access_token)

springBoot集成oAuth2,系列八(使用redis存储token的时候,报错: java.lang.NoSuchMethodError: org.springframework.data.redis.connection.RedisConnection.set)

集成oAuth2后发现返回数据是这样的,缺失了refresh_token返回值

image.png

为什么网上是有的,如下

image.png

解决办法,authorizedGrantTypes加refresh_token就可以了(版本:2.3.1)

.authorizedGrantTypes("password","authorization_code","refresh_token");

package org.mayanze.dcims.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;

@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private AuthenticationManager authenticationManager;//密码模式需要注入认证管理器

    @Autowired
    public PasswordEncoder passwordEncoder;

    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients
                .inMemory()
                .withClient("first-client")
                .secret(passwordEncoder.encode("noonewilleverguess"))
                .scopes("resource:read")
                .authorizedGrantTypes("password","authorization_code","refresh_token");
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints.authenticationManager(authenticationManager);
    }
}

解决过程

网上找了一大堆,什么重写DefaultTokenServices。。。等等等等,结果都不行

image.png

偷懒不成,查看源码:

1、自然是入口开始TokenEndpoint.postAccessToken方法

image.png

2、根据getTokenGranter().grant 跳转到AbstractTokenGranter.grant方法

image.png

3、再跳转到AbstractTokenGranter.getAccessToken方法

image.png

4、跳转到DefaultTokenServices.createAccessToken

image.png

5、注意重启项目后再调试,否则这块会进入第一个if;我重启后调试的,所以会走创建createRefreshToken方法

image.png

6、跳转到DefaultTokenServices.createRefreshToken,划重点,就是这个判断isSupportRefreshToken,字面意思就是,是否支持RefreshToken

image.png

7、跳转到DefaultTokenServices.isSupportRefreshToken,是否包含"refresh_token"

image.png

放个特写,怎么这么熟悉呢?

image.png

不是在AuthorizationServerConfig配置过嘛

image.png

好的,明白了