博客
关于我
【RestTemplate】RestTemplate访问需要OAuth2授权的服务
阅读量:486 次
发布时间:2019-03-06

本文共 2071 字,大约阅读时间需要 6 分钟。

文章目录

RestTemplate访问需要OAuth2授权的服务

概述

随着微服务安全性的增强,需要携带token才能访问其API,然而RestTemplate默认并不会将 token 放到 Header 中,那么如何使用RestTemplate实现自动设置授权信息并访问需要OAuth2授权的服务呢?

本文重点讲述如何通过OAuth2RestTemplate实现自动设置授权信息,并访问需要OAuth2的client模式授权的服务。需要重点理解下面两点:

  • OAuth2.0配置
  • OAuth2RestTemplate

本文依赖:

  • spring-boot-starter-parent:2.4.2
  • spring-cloud-starter-oauth2:2.2.4.RELEASE

示例

OAuth2.0相关配置

引入依赖

org.springframework.cloud
spring-cloud-starter-oauth2
2.2.4.RELEASE

配置application.yml

security:  oauth2:    client:      client-id: car-client      client-secret: 123456      grant-type: authorization_code #client_credentials      user-authorization-uri: ${   auth.service}/oauth/authorize #请求认证的地址      access-token-uri: ${   auth.service}/oauth/token #请求令牌的地址      pre-established-redirect-uri: ${   client.service}/callback      scope:        - allauth.service: http://localhost:8080client.service: http://localhost:8091

OAuth2RestTemplate

编写OAuth2RestTemplateConfiguration(重点)

@Configurationpublic class OAuth2RestTemplateConfiguration {       @Resource    private ClientCredentialsResourceDetails clientCredentialsResourceDetails;    @Bean    public OAuth2RestTemplate clientCredentialsRestTemplate() {           return new OAuth2RestTemplate(clientCredentialsResourceDetails);    }    @Bean    @ConfigurationProperties("security.oauth2.client")    //@ConfigurationProperties("spring.security.oauth2.client.registration.github")    public AuthorizationCodeResourceDetails google() {           return new AuthorizationCodeResourceDetails();    }    @Bean    public OAuth2RestTemplate authorizationCodeRestTemplate(AuthorizationCodeResourceDetails authorizationCodeResourceDetails) {           return new OAuth2RestTemplate(clientCredentialsResourceDetails);    }}

拓展

RestTemplate访问需要Basic授权的服务

RestTemplate restTemplate = new RestTemplate();restTemplate.getInterceptors().add(new BasicAuthenticationInterceptor("username", "password"));

或者

RestTemplate restTemplate = new RestTemplateBuilder().basicAuthentication("username", "password").build();

参考

转载地址:http://fexdz.baihongyu.com/

你可能感兴趣的文章
MySQL 深度分页性能急剧下降,该如何优化?
查看>>
MySQL 添加列,修改列,删除列
查看>>
mysql 添加索引
查看>>
MySQL 添加索引,删除索引及其用法
查看>>
mysql 状态检查,备份,修复
查看>>
MySQL 用 limit 为什么会影响性能?
查看>>
MySQL 用 limit 为什么会影响性能?有什么优化方案?
查看>>
MySQL 用户权限管理:授权、撤销、密码更新和用户删除(图文解析)
查看>>
mysql 用户管理和权限设置
查看>>
MySQL 的 varchar 水真的太深了!
查看>>
mysql 的GROUP_CONCAT函数的使用(group_by 如何显示分组之前的数据)
查看>>
MySQL 的instr函数
查看>>
MySQL 的mysql_secure_installation安全脚本执行过程介绍
查看>>
MySQL 的Rename Table语句
查看>>
MySQL 的全局锁、表锁和行锁
查看>>
mysql 的存储引擎介绍
查看>>
MySQL 的存储引擎有哪些?为什么常用InnoDB?
查看>>
Mysql 知识回顾总结-索引
查看>>
Mysql 笔记
查看>>
MySQL 精选 60 道面试题(含答案)
查看>>