二、​​Spring Cloud OAuth2 token存数据库实现​​​ 三、​​Spring Cloud Oauth2 JWT 实现​


学习一下Spring Cloud OAuth2,我们分三个项目 eureka-server、service-auth、service-hi

  Spring Cloud OAuth2_xml g9.png

1. 创建eureka-server项目

选择依赖 spring-cloud-starter-netflix-eureka-server

1.1 启动类里添加注释

@SpringBootApplication
@EnableEurekaServer
public class EurekaServerApplication {

public static void main(String[] args) {
SpringApplication.run(EurekaServerApplication.class, args);
}
}

1.2 application.yml

spring:
application:
name: eureka-server
server:
port: 8761
eureka:
instance:
hostname: localhost
client:
service-url:
defaultZone: http://localhost:8761/eureka/
fetch-registry: false
register-with-eureka: false

配置完成可以访问 ​​http://localhost:8761​

2 创建service-auth项目

2.1 用于获取授权token,项目上目录结构:

  Spring Cloud OAuth2_maven_02 g4.png


这里有个有趣的地方,如果包名config和customImpl和启动类不在同一个根包下,会扫不到包,此时必须在启动类上增加 ​​@ComponentScan(basePackages = "包名")​


2.2 创建项目依赖

  • spring-boot-starter-data-redis把token存到redis中
  • spring-cloud-starter-netflix-eureka-client做为EurekaClient
  • spring-cloud-starter-oauth2是对spring-cloud-starter-security、spring-security-oauth2、spring-security-jwt这3个依赖的整合
  • spring-boot-starter-actuator

完整pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.uaa.service</groupId>
<artifactId>uaa-service</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>uaa-service</name>
<description>Demo project for Spring Boot</description>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.4.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<spring-cloud.version>Finchley.SR1</spring-cloud.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId