使用背景 :公司有个开放平台,若要访问开放平台,必须先要获取授权访问令牌(也就是下面说的:access_token)。公司的授权系统是用spring oauth2.0实现的,今天就不讲这个项目,网上比较多。今天主要是讲下如何用spring OAuth2.0 Client 组件会去实现高效获取access_token。
以下是实现代码:
1.项目启动后,从oauth.properties获取相关的信息(如公钥、私钥等信息),然后实例化OAuth2RestTemplate,主要是通过OAuth2RestTemplate这个类去获取access_token,.
@EnableOAuth2Client
@Configuration
@Component
public class Oauth2Config{
private final static Logger logger = Logger.getLogger(Oauth2Config.class);
private static String location = "classpath:config/*/oauth.properties";
private static Map<String,String> oauthInfo = new HashMap<String,String>();
@Autowired
private OAuth2ClientContext oauth2Context;
/**
* 获取配置文件信息
*/
static{
ResourcePatternResolver patternResolver = new PathMatchingResourcePatternResolver();
Resource[] resources;
try {
resources = patternResolver.getResources(location);
location = resources[0].getFile().getAbsolutePath();
logger.info("location" + location);
Properties props = new Properties();
try {
if(location.contains("dev")){
props = PropertiesLoaderUtils.loadAllProperties("config/dev/oauth.properties");
}else if(location.contains("test")){
props = PropertiesLoaderUtils.loadAllP