Ouath2.0在SpringCloud下獲取授權碼,驗證授權碼,刷新授權碼
本文不主要介紹SpringCloud的其他組件,只展示Ouath2.0的集成代碼,並演示授權碼的獲取,檢驗,刷新,展示其他模塊是因爲在Ouath2.0裏面怕有人問這數據從哪裏來的,如果覺得環境太麻煩,就直接看Ouath2.0服務的CustomUserService類實現,寫些死數據就不需要集成其他服務依賴了,只需要關注Ouath2.0服務即可。
1. 環境介紹
JAVA語言,JDK1.8,IDEA2018.2.4,SpringBoot,SpringCloud,PostMan接口測試,谷歌瀏覽器,
2. 項目工程圖
- Eureka註冊中心
- Ouath2.0服務
- 用戶服務模塊
用戶服務模塊內容不利於介紹Ouath2.0展示,用戶服務模塊的主要作用是提供Ouath2.0的用戶查詢與角色查詢,並把查詢的數據注入Ouath2.0裏面去,這裏展示主要代碼接口。 Ouath2.0服務主要是Fegin調用這個接口獲取用戶數據。
//根據郵箱號碼獲取管理員具體信息
@PostMapping("/queryManagerUserInfo")
String queryManagerUserInfo(@RequestParam("email") String email);
//根據管理員ID獲取相匹配的所有角色
@PostMapping("/queryManagerUserAndRole")
String queryManagerUserAndRole(@RequestParam("id") Long id);
展示一下我的接口請求的效果
上面的請求結果中演示的話其實並不需要這麼多數據,第一個接口最主要的數據是email和password,第二個接口最主要的數據是codeName。
3. Ouath2.0服務模塊介紹
項目圖
POM文件
<?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.fenghua</groupId>
<artifactId>tm_springcloud_oauth2_service</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.1.RELEASE</version>
</parent>
<!-- 管理依賴 -->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Finchley.M7</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<dependencies>
<!-- SpringBoot整合Web組件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
<!-->spring-boot 整合security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- spring-cloud-starter-oauth2 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<!-- springboot整合freemarker -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.fenghua</groupId>
<artifactId>tm_springcloud_api_user</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.49</version>
</dependency>
</dependencies>
<!-- 注意: 這裏必須要添加, 否者各種依賴有問題 -->
<repositories>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/libs-milestone</url>
<snapshots>
<enabled>false</enabled>
</snapshots>
</repository>
</repositories>
</project>
application.yml
server:
port: 8500
spring:
datasource:
hikari:
connection-test-query: SELECT 1
minimum-idle: 1
maximum-pool-size: 5
pool-name: dbcp1
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/tm_springcloud_oauth2?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2b8
username: root
password: 123456
application:
name: tm-fenghua-oauth2
jackson:
time-zone: GMT+8
###註冊中心
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8100/eureka
AppOauth2Server類
package com.fenghua.oauth2;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EnableFeignClients
@EnableEurekaClient
public class AppOauth2Server {
public static void main(String[] args) {
SpringApplication.run(AppOauth2Server.class, args);
}
}
IUserServiceFegin類
package com.fenghua.oauth2.fegin;
import com.fenghua.oauth2.fegin.fallback.UserFallBack;
import com.tm.user.api.IUserApi;
import org.springframework.cloud.openfeign.FeignClient;
/************************
* @作者 fenghua
* @創建日期 2019/5/13 14:44
* @功能 RPC遠程調用
************************/
@FeignClient(value = "tm-fenghua-user",fallback = UserFallBack.class)
public interface IUserServiceFegin extends IUserApi {
}
UserFallBack類
package com.fenghua.oauth2.fegin.fallback;
import com.alibaba.fastjson.JSON;
import com.fenghua.oauth2.fegin.IUserServiceFegin;
import com.tm.common.Response;
import com.tm.common.ResponseCode;
import org.springframework.stereotype.Component;
/************************
* @作者 fenghua
* @創建日期 2019/5/13 14:44
* @功能 服務降級處理
************************/
@Component
public class UserFallBack implements IUserServiceFegin {
@Override
public String queryManagerUserInfo(String email) {
return JSON.toJSONString(new Response(ResponseCode.SERVER_DOWNGRADE, "服務降級"));
}
@Override
public String queryManagerUserAndRole(Long id) {
return JSON.toJSONString(new Response(ResponseCode.SERVER_DOWNGRADE, "服務降級"));
}
}
ResManagerUser類
package com.fenghua.oauth2.config.entity;
import java.io.Serializable;
public class ResManagerUser implements Serializable {
/**
* code : 10001
* data : {"address":"貴陽學院","createtime":"2019-05-22T16:02:36","email":"[email protected]","id":2,"name":"恩華","password":"123456","sign":false,"tel":"1111111111"}
* msg : 成功
*/
private int code;
private DataBean data;
private String msg;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public DataBean getData() {
return data;
}
public void setData(DataBean data) {
this.data = data;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public static class DataBean implements Serializable {
/**
* address : 貴陽學院
* createtime : 2019-05-22T16:02:36
* email : [email protected]
* id : 2
* name : 風華
* password : 123456
* sign : false
* tel : 1111111111
*/
private String address;
private String createtime;
private String email;
private int id;
private String name;
private String password;
private boolean sign;
private String tel;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCreatetime() {
return createtime;
}
public void setCreatetime(String createtime) {
this.createtime = createtime;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isSign() {
return sign;
}
public void setSign(boolean sign) {
this.sign = sign;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
}
}
ResRole類
package com.fenghua.oauth2.config.entity;
import java.io.Serializable;
import java.util.List;
public class ResRole implements Serializable {
/**
* code : 10001
* data : [{"codeName":"ROLE_USER","id":2,"name":"系統管理員","pid":1},{"codeName":"Admin","id":4,"name":"管理員","pid":1}]
* msg : 成功
*/
private int code;
private String msg;
private List<DataBean> data;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public List<DataBean> getData() {
return data;
}
public void setData(List<DataBean> data) {
this.data = data;
}
public static class DataBean implements Serializable {
/**
* codeName : ROLE_USER
* id : 2
* name : 系統管理員
* pid : 1
*/
private String codeName;
private int id;
private String name;
private int pid;
public String getCodeName() {
return codeName;
}
public void setCodeName(String codeName) {
this.codeName = codeName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPid() {
return pid;
}
public void setPid(int pid) {
this.pid = pid;
}
}
}
好了,上面都是一些項目基本配置,開始我們Ouath2.0相關幾個類了,重點喲
AuthorizationServerConfig類
package com.fenghua.oauth2.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
import javax.sql.DataSource;
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
@Autowired
@Qualifier("dataSource")
private DataSource dataSource;
@Bean
public TokenStore tokenStore() {
return new JdbcTokenStore(dataSource);
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.jdbc(dataSource);
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
endpoints.authenticationManager(authenticationManager())
.allowedTokenEndpointRequestMethods(HttpMethod.GET, HttpMethod.POST)
.tokenStore(tokenStore())
.userDetailsService(userDetailsService());
}
@Bean
UserDetailsService userDetailsService() {
return new CustomUserService();
}
@Override
public void configure(AuthorizationServerSecurityConfigurer security) {
security.tokenKeyAccess("permitAll()")
.checkTokenAccess("permitAll()")
.allowFormAuthenticationForClients();
}
@Bean
AuthenticationManager authenticationManager() {
return authentication -> daoAuhthenticationProvider().authenticate(authentication);
}
@Bean
public AuthenticationProvider daoAuhthenticationProvider() {
DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
daoAuthenticationProvider.setUserDetailsService(userDetailsService());
daoAuthenticationProvider.setHideUserNotFoundExceptions(false);
daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
return daoAuthenticationProvider;
}
@Bean
PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
WebSecurityConfig類
package com.fenghua.oauth2.config;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.stereotype.Component;
@Component
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 攔截所有請求,並使用httpBasic方式登陸
*
* @param http
* @throws Exception
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/**")
.fullyAuthenticated()
.and().httpBasic();
}
}
SecurityUser類
package com.fenghua.oauth2.config.entity;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
@Data
public class SecurityUser implements Serializable, UserDetails {
//密碼需要加密
public static final PasswordEncoder PASSWORD_ENCODER = new BCryptPasswordEncoder();
private static final long serialVersionUID = 1L;
/**
* 郵箱號碼
*/
private String email;
/**
* 登錄密碼
*/
private String password;
/**
* 使用狀態(0正常使用中)
*/
private Boolean sign;
/**
* 權限集合
*/
private List<ResRole.DataBean> resRoleList;
public void setPassword(String password) {
this.password = PASSWORD_ENCODER.encode(password);
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
//將用戶角色作爲權限
List<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
List<ResRole.DataBean> dataBeans = this.getResRoleList();
for (ResRole.DataBean dataBean : dataBeans) {
System.out.println(dataBean.getCodeName());
auths.add(new SimpleGrantedAuthority(dataBean.getCodeName()));
}
return auths;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getUsername() {
return email;
}
//賬戶是否過期,過期無法驗證
@Override
public boolean isAccountNonExpired() {
return true;
}
//指定用戶是否被鎖定或者解鎖,鎖定的用戶無法進行身份驗證
@Override
public boolean isAccountNonLocked() {
return true;
}
//指示是否已過期的用戶的憑據(密碼),過期的憑據防止認證
@Override
public boolean isCredentialsNonExpired() {
return true;
}
//是否被禁用,禁用的用戶不能身份驗證
@Override
public boolean isEnabled() {
return true;
}
}
CustomUserService類
繼承UserDetailsService接口,實現loadUserByUsername方法,可以自己封裝死數據,這樣就不需要從其他服務調用
package com.fenghua.oauth2.config;
import com.alibaba.fastjson.JSON;
import com.fenghua.oauth2.config.entity.ResManagerUser;
import com.fenghua.oauth2.config.entity.ResRole;
import com.fenghua.oauth2.config.entity.SecurityUser;
import com.fenghua.oauth2.fegin.IUserServiceFegin;
import com.tm.common.ResponseCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.util.StringUtils;
public class CustomUserService implements UserDetailsService {
@Autowired
private IUserServiceFegin iUserServiceFegin;
@Override
public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
SecurityUser securityUser = null;
//查詢用戶
String stringUser = iUserServiceFegin.queryManagerUserInfo(s);
ResManagerUser resManagerUser = JSON.parseObject(stringUser, ResManagerUser.class);
if (resManagerUser != null && resManagerUser.getCode() == ResponseCode.SUCCESS.getCode()) {
//從返回接口裏面獲取用戶數據
if (resManagerUser.getData() == null || StringUtils.isEmpty(resManagerUser.getData().getId()) || StringUtils.isEmpty(resManagerUser.getData().getEmail())) {
throw new UsernameNotFoundException("用戶不存在");
} else {
//根據獲取的用戶ID獲取該用戶的角色列表
String stringRole = iUserServiceFegin.queryManagerUserAndRole((long) resManagerUser.getData().getId());
ResRole resRole = JSON.parseObject(stringRole, ResRole.class);
if (resRole != null && resRole.getCode() == ResponseCode.SUCCESS.getCode()) {
//從返回接口裏面獲取角色數據
if (resRole.getData() != null && resRole.getData().size() > 0) {
securityUser = new SecurityUser();
securityUser.setEmail(resManagerUser.getData().getEmail());
securityUser.setPassword(resManagerUser.getData().getPassword());
securityUser.setSign(resManagerUser.getData().isSign());
securityUser.setResRoleList(resRole.getData());
} else {
throw new UsernameNotFoundException("角色數據解析失敗");
}
} else {
throw new UsernameNotFoundException("角色數據查詢失敗," + resRole.getMsg());
}
}
} else {
throw new UsernameNotFoundException("用戶數據解析失敗");
}
return securityUser;
}
}
Ouath2.0是通過數據庫來進行管理授權碼的
這個數據庫的結構是根據官方,但在我的數據庫有些字段類型不同,我進行了一定的修改。
官方鏈接:
/*
Navicat Premium Data Transfer
Source Server : localhost
Source Server Type : MariaDB
Source Server Version : 100212
Source Host : 127.0.0.1:3306
Source Schema : tm_springcloud_oauth2
Target Server Type : MariaDB
Target Server Version : 100212
File Encoding : 65001
Date: 28/05/2019 20:20:57
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for clientdetails
-- ----------------------------
DROP TABLE IF EXISTS `clientdetails`;
CREATE TABLE `clientdetails` (
`appId` varchar(256) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
`resourceIds` varchar(256) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`appSecret` varchar(256) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`scope` varchar(256) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`grantTypes` varchar(256) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`redirectUrl` varchar(256) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`authorities` varchar(256) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`access_token_validity` int(11) NULL DEFAULT NULL,
`refresh_token_validity` int(11) NULL DEFAULT NULL,
`additionalInformation` varchar(4096) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`autoApproveScopes` varchar(256) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`appId`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Table structure for oauth_access_token
-- ----------------------------
DROP TABLE IF EXISTS `oauth_access_token`;
CREATE TABLE `oauth_access_token` (
`token_id` varchar(256) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`token` blob NULL DEFAULT NULL,
`authentication_id` varchar(256) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
`user_name` varchar(256) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`client_id` varchar(256) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`authentication` blob NULL DEFAULT NULL,
`refresh_token` varchar(256) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`authentication_id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Table structure for oauth_approvals
-- ----------------------------
DROP TABLE IF EXISTS `oauth_approvals`;
CREATE TABLE `oauth_approvals` (
`userId` varchar(256) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`clientId` varchar(256) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`scope` varchar(256) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`status` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`expiresAt` timestamp(0) NOT NULL DEFAULT current_timestamp ON UPDATE CURRENT_TIMESTAMP,
`lastModifiedAt` timestamp(0) NOT NULL DEFAULT '0000-00-00 00:00:00'
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Table structure for oauth_client_details
-- ----------------------------
DROP TABLE IF EXISTS `oauth_client_details`;
CREATE TABLE `oauth_client_details` (
`client_id` varchar(256) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
`resource_ids` varchar(256) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`client_secret` varchar(256) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`scope` varchar(256) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`authorized_grant_types` varchar(256) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`web_server_redirect_uri` varchar(256) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`authorities` varchar(256) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`access_token_validity` int(11) NULL DEFAULT NULL,
`refresh_token_validity` int(11) NULL DEFAULT NULL,
`additional_information` varchar(4096) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`autoapprove` varchar(256) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`client_id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Table structure for oauth_client_token
-- ----------------------------
DROP TABLE IF EXISTS `oauth_client_token`;
CREATE TABLE `oauth_client_token` (
`token_id` varchar(256) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`token` blob NULL DEFAULT NULL,
`authentication_id` varchar(256) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NOT NULL,
`user_name` varchar(256) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`client_id` varchar(256) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
PRIMARY KEY (`authentication_id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Table structure for oauth_code
-- ----------------------------
DROP TABLE IF EXISTS `oauth_code`;
CREATE TABLE `oauth_code` (
`code` varchar(256) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`authentication` blob NULL DEFAULT NULL
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Table structure for oauth_refresh_token
-- ----------------------------
DROP TABLE IF EXISTS `oauth_refresh_token`;
CREATE TABLE `oauth_refresh_token` (
`token_id` varchar(256) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL,
`token` blob NULL DEFAULT NULL,
`authentication` blob NULL DEFAULT NULL
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic;
SET FOREIGN_KEY_CHECKS = 1;
獲取 授權碼前用戶需要去註冊獲取AppID與AppKey,在Ouath2.0裏面對應字段是client_id,client_secret,所以需要提前向數據庫插入數據
我們數據準備好後就啓動項目與對應的依賴服務項目
4.獲取授權碼演示
- 通過授權獲取到授權碼
點擊登錄後
Approve 允許,Deny 拒絕,選擇Approve,點擊按鈕
通過code獲取授權碼
- 通過密碼模式獲取驗證碼
- 驗證Token是否有效
http://localhost:8500/oauth/check_token?token=246f9d30-0585-4865-8f3b-7333a6565390
- 刷新Token