1 Oauth2

1.1 什么是Oauth2?

  O(pen)Auth(开发授权) 是一个公开的授权标准,Oauth2.0是Oauth的延续版本,早期的Oauth1.0已经被淘汰。现在市面上使用的都是Oauth2,这个Oauth2.0是一个授权协议,它规定了多种授权模式和授权方法,这个标准下很多公司都开放了授权登录第三方网站的功能。比如我们常用的授权模式有:

  • 扫码登录

  • 用户名和密码

  • 客户端授权等

我们添加Oauth2依赖,添加之后当前项目会自动添加一些控制器依赖,比较常见的控制器路径有:

  • /oauth/token:向这个路径发送请求,返回令牌

  • /oauth/check_token:给定一个令牌做参数,能够返回当前用户信息

1.2 Spring Cloud Security

  支持微服务的Spring Security安全框架:Spring Cloud Security,我们单体项目使用了Spring Security安全框架管理登录和权限,在微服务的框架下,我们需要使用支持微服务的版本,再结合Oauth2标准,实现使用Token的授权过程。

具体的Spring Cloud Security结合Oauth2标准实现单点登录思路如下:

微服务(五)-Oauth2、Spring Cloud Security、JWT令牌_maven

  上面的模式中,我们创建的微服务项目分成两大类:

  1. 授权服务器:接收用户名、密码,验证登录,并返回令牌---获取令牌

  2. 资源服务器:在用户请求时,解析令牌,获得用户信息,执行业务操作---解析令牌

  最后,利用Oauth2中自带的控制器提供的端点(暴露的Rest接口)。

1.3 创建授权服务器

1.3.1 创建knows-auth

  在父项目knows上单击右键,新建module:knows-auth,什么都不勾选,完成项目的创建。

微服务(五)-Oauth2、Spring Cloud Security、JWT令牌_服务器_02

父子相认:在父项目的knows的pom.xml文件中添加子项目依赖knows-auth

 <module>knows-auth</module>

子项目knows-auth的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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
     <modelVersion>4.0.0</modelVersion>
     <parent>
         <groupId>cn.tedu</groupId>
         <artifactId>knows</artifactId>
         <version>0.0.1-SNAPSHOT</version>
         <relativePath/> <!-- lookup parent from repository -->
     </parent>
     <groupId>cn.tedu</groupId>
     <artifactId>knows-auth</artifactId>
     <version>0.0.1-SNAPSHOT</version>
     <name>knows-auth</name>
     <description>Demo project for Spring Boot</description>
 
     <dependencies>
         <!-- spring cloud security 依赖 -->
         <dependency>
             <groupId>org.springframework.cloud</groupId>
             <artifactId>spring-cloud-starter-security</artifactId>
         </dependency>
         <!-- 添加支持Oauth2开放标准的实现 -->
         <dependency>
             <groupId>org.springframework.cloud</groupId>
             <artifactId>spring-cloud-starter-oauth2</artifactId>
         </dependency>
         <!-- jwt令牌支持 -->
         <dependency>
             <groupId>org.springframework.security</groupId>
             <artifactId>spring-security-jwt</artifactId>
         </dependency>
  <!-- 数据库相关依赖 -->
         <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-jdbc</artifactId>
         </dependency>
         <dependency>
             <groupId>mysql</groupId>
             <artifactId>mysql-connector-java</artifactId>
         </dependency>
         <!--springboot内置tomcat和SpringMVC,可进行启动web服务-->
         <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-web</artifactId>
         </dependency>
          <!--注册到nacos-->
         <dependency