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
