Ouath2.0在SpringCloud下验证获取授权码

Ouath2.0在SpringCloud下获取授权码,验证授权码,刷新授权码

本文不主要介绍SpringCloud的其他组件,只展示Ouath2.0的集成代码,并演示授权码的获取,检验,刷新,展示其他模块是因为在Ouath2.0里面怕有人问这数据从哪里来的,如果觉得环境太麻烦,就直接看Ouath2.0服务的CustomUserService类实现,写些死数据就不需要集成其他服务依赖了,只需要关注Ouath2.0服务即可。推荐一篇文章:Spring Security Oauth2和Spring Boot实现单点登录


1. 环境介绍
JAVA语言,JDK1.8,IDEA2018.2.4,SpringBoot,SpringCloud,PostMan接口测试,谷歌浏览器,

2. 项目工程图

Eureka注册中心

 Ouath2.0服务

 用户服务模块

用户服务模块内容不利于介绍Ouath2.0展示,用户服务模块的主要作用是提供Ouath2.0的用户查询与角色查询,并把查询的数据注入Ouath2.0里面去,这里展示主要代码接口。 Ouath2.0服务主要是Fegin调用这个接口获取用户数据。

1
2
3
4
5
6
7
//根据邮箱号码获取管理员具体信息
@PostMapping("/queryManagerUserInfo")
String queryManagerUserInfo(@RequestParam("email") String email);
     
//根据管理员ID获取相匹配的所有角色
@PostMapping("/queryManagerUserAndRole")
String queryManagerUserAndRole(@RequestParam("id") Long id);

 展示一下我的接口请求的效果

 

 上面的请求结果中演示的话其实并不需要这么多数据,第一个接口最主要的数据是email和password,第二个接口最主要的数据是codeName。

3. Ouath2.0服务模块介绍
项目图

 

 POM文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<?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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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类

1
2
3
4
5
6
7
8
9
10
11
12
package com.fenghua.oauth2.fegin;
 
import com.fenghua.oauth2.fegin.fallback.UserFallBack;
import com.tm.user.api.IUserApi;
import org.springframework.cloud.openfeign.FeignClient;
 
/************************
 * @功能 RPC远程调用
 ************************/
@FeignClient(value = "tm-fenghua-user",fallback = UserFallBack.class)
public interface IUserServiceFegin extends IUserApi {
}

 UserFallBack类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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;
 
/************************
 * @功能 服务降级处理
 ************************/
 
@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类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
package com.fenghua.oauth2.config.entity;
 
import java.io.Serializable;
 
 
public class ResManagerUser implements Serializable {
 
 
    /**
     * code : 10001
     * data : {"address":"guiyang_university","createtime":"2020-08-18T16:02:36","email":"123456@qq.com","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 : guiyang_university
         * createtime : 2020-08-18T16:02:36
         * email : 123456@qq.com
         * id : 2
         * name : 47Gamer
         * 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类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
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类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
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);
      // clients.inMemory()//配置在内存里,后面修改为数据库里
        //~============== 注册【客户端应用】,使客户端应用能够访问认证服务器 ===========
        //  .withClient("sca_app")//客户端id
        // .secret(passwordEncoder.encode("secret_key")) //客户端密钥
        // .scopes("all","read","write") //sca_app有哪些权限
        // .accessTokenValiditySeconds(3600) //token的有效期
        // .resourceIds("system-service") //资源服务器的id。发给sca_app的token,能访问哪些资源服务器,可以多个
        //.authorizedGrantTypes("authorization_code","password","client_creentials","implicit","refresh_token")//授权方式,再给orderApp做授权的时候可以用哪种授权方式授权
        //.autoApprove(false)  // false 跳转到授权页面
        // .redirectUris("http://www.baidu.com");// 加上验证回调地址
        //~=============客户端应用配置结束 =====================
     
    }
 
    @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()") // 开启/oauth/token_key验证端口无权限访问
                .checkTokenAccess("permitAll()") //"isAuthenticated()" // 开启/oauth/check_token验证端口认证权限访问
                .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类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
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方法,可以自己封装死数据,这样就不需要从其他服务调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
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是通过数据库来进行管理授权码的
这个数据库的结构是根据官方,但在我的数据库有些字段类型不同,我进行了一定的修改。
官方链接:

https://github.com/spring-projects/spring-security-oauth/blob/master/spring-security-oauth2/src/test/resources/schema.sql

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
/*
 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
 
*/
 
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.获取授权码演示

通过授权获取到授权码

http://localhost:8500/oauth/authorize?response_type=code&client_id=guiyang_university&redirect_uri=http://www.baidu.com&scope=all

 点击登录后

 

 

Approve 允许,Deny 拒绝,选择Approve,点击按钮

 

通过code获取授权码

http://localhost:8500/oauth/token?grant_type=authorization_code&code=nFdtJi&redirect_uri=http://www.baidu.com&scpoe=all&client_id=guiyang_university&client_secret=123456

 

 通过密码模式获取验证码

http://localhost:8500/oauth/token

 

 验证Token是否有效

http://localhost:8500/oauth/check_token?token=246f9d30-0585-4865-8f3b-7333a6565390

 

刷新Token

http://localhost:8500/oauth/token?grant_type=refresh_token&refresh_token=279317ca-4019-41a2-8b4c-919e8b7ddd3a&client_id=guiyang_university&client_secret=123456

 

posted @   47号Gamer丶  阅读(325)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示