网关安全(三)-改造微服务使其成为OAuth2资源服务器
1、将微服务改造为OAuth2资源服务器
以订单服务为例,将其修改为OAuth2资源服务器
1.1、pom中添加spring-cloud-starter-oauth2依赖
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.2.0.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Greenwich.SR2</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<properties>
<java.version>1.8</java.version>
<maven.compiler.source>${java.version}</maven.compiler.source>
<maven.compiler.target>${java.version}</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
</dependencies>
1.2、ResourceServerConfig 资源服务器配置类
/** * 资源服务器配置 * * @author caofanqi * @date 2020/2/1 20:10 */ @Configuration @EnableResourceServer public class ResourceServerConfig extends ResourceServerConfigurerAdapter { @Override public void configure(ResourceServerSecurityConfigurer resources) throws Exception { //该资源服务器id resources.resourceId("order-server"); } }
1.3、WebSecurityConfig Web安全配置类
/** * Web安全配置类 * * @author caofanqi * @date 2020/2/1 20:13 */ @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { /** * 使用OAuth2AuthenticationManager,需要到认证服务器校验用户信息 */ @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { OAuth2AuthenticationManager authenticationManager = new OAuth2AuthenticationManager(); authenticationManager.setTokenServices(tokenServices()); return authenticationManager; } /** * 远程校验令牌相关配置 */ @Bean public ResourceServerTokenServices tokenServices(){ RemoteTokenServices tokenServices = new RemoteTokenServices(); tokenServices.setClientId("orderService"); tokenServices.setClientSecret("123456"); tokenServices.setCheckTokenEndpointUrl("http://127.0.0.1:9020/oauth/check_token"); return tokenServices; } }
1.4、可以在Controller方法中通过@AuthenticationPrincipal 获取用户名
@PostMapping public OrderDTO create(@RequestBody OrderDTO orderDTO, @AuthenticationPrincipal String username) { log.info("username is :{}", username); PriceDTO price = restTemplate.getForObject("http://127.0.0.1:9070/prices/" + orderDTO.getProductId(), PriceDTO.class); log.info("price is : {}", price.getPrice()); return orderDTO; }
1.5、启动项目直接访问创建订单,此时返回401,没有进行身份认证,说明我们配置的资源服务器生效了

1.6、通过Authorization请求头,添加从认证服务器获取的令牌,访问成功,控制台打印出令牌所有者zhangsan。


项目源码:https://github.com/caofanqi/study-security/tree/dev-ResourceServer

浙公网安备 33010602011771号