步骤
1、初始化 OAuth2 相关表
建表脚本如下:
CREATE TABLE `clientdetails` (
`appId` varchar(128) NOT NULL,
`resourceIds` varchar(256) DEFAULT NULL,
`appSecret` varchar(256) DEFAULT NULL,
`scope` varchar(256) DEFAULT NULL,
`grantTypes` varchar(256) DEFAULT NULL,
`redirectUrl` varchar(256) DEFAULT NULL,
`authorities` varchar(256) DEFAULT NULL,
`access_token_validity` int(11) DEFAULT NULL,
`refresh_token_validity` int(11) DEFAULT NULL,
`additionalInformation` varchar(4096) DEFAULT NULL,
`autoApproveScopes` varchar(256) DEFAULT NULL,
PRIMARY KEY (`appId`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `oauth_access_token` (
`token_id` varchar(256) DEFAULT NULL,
`token` blob,
`authentication_id` varchar(128) NOT NULL,
`user_name` varchar(256) DEFAULT NULL,
`client_id` varchar(256) DEFAULT NULL,
`authentication` blob,
`refresh_token` varchar(256) DEFAULT NULL,
PRIMARY KEY (`authentication_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `oauth_approvals` (
`userId` varchar(256) DEFAULT NULL,
`clientId` varchar(256) DEFAULT NULL,
`scope` varchar(256) DEFAULT NULL,
`status` varchar(10) DEFAULT NULL,
`expiresAt` timestamp NULL DEFAULT NULL,
`lastModifiedAt` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `oauth_client_details` (
`client_id` varchar(128) NOT NULL,
`resource_ids` varchar(256) DEFAULT NULL,
`client_secret` varchar(256) DEFAULT NULL,
`scope` varchar(256) DEFAULT NULL,
`authorized_grant_types` varchar(256) DEFAULT NULL,
`web_server_redirect_uri` varchar(256) DEFAULT NULL,
`authorities` varchar(256) DEFAULT NULL,
`access_token_validity` int(11) DEFAULT NULL,
`refresh_token_validity` int(11) DEFAULT NULL,
`additional_information` varchar(4096) DEFAULT NULL,
`autoapprove` varchar(256) DEFAULT NULL,
PRIMARY KEY (`client_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `oauth_client_token` (
`token_id` varchar(256) DEFAULT NULL,
`token` blob,
`authentication_id` varchar(128) NOT NULL,
`user_name` varchar(256) DEFAULT NULL,
`client_id` varchar(256) DEFAULT NULL,
PRIMARY KEY (`authentication_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `oauth_code` (
`code` varchar(256) DEFAULT NULL,
`authentication` blob
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `oauth_refresh_token` (
`token_id` varchar(256) DEFAULT NULL,
`token` blob,
`authentication` blob
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
2、数据库中配置客户端
在表 oauth_client_details
中增加一条客户端配置记录,需要设置的字段如下:
client_id
:客户端标识client_secret
:客户端安全码,此处不能是明文,需要加密scope
:客户端授权范围authorized_grant_types
:客户端授权类型web_server_redirect_uri
:服务器回调地址
获得安全码加密信息,填到client_secret字段中
new BCryptPasswordEncoder().encode("secret")
3、POM
由于使用了 JDBC 存储,我们需要增加相关依赖,数据库连接池使用 HikariCP
<dependency>
<groupId>com.zaxxer</groupId>
<artifactId>HikariCP</artifactId>
<version>${hikaricp.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
<exclusions>
<!-- 排除 tomcat-jdbc 以使用 HikariCP -->
<exclusion>
<groupId>org.apache.tomcat</groupId>
<artifactId>tomcat-jdbc</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.version}</version>
</dependency>
4、application.yml
由于Spring无法识别出spring.datasource.jdbc-url的属性,只能识别url,但是oauth2框架必须要求使用jdbc-url,所以需要在配置类中重写DataSource。
spring:
application:
name: oauth2-server
datasource:
type: com.zaxxer.hikari.HikariDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
jdbc-url: jdbc:mysql://localhost:3306/oauth2?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=utf-8&useSSL=false
username: root
password: root
hikari:
minimum-idle: 5
idle-timeout: 600000
maximum-pool-size: 10
auto-commit: true
pool-name: MyHikariCP
max-lifetime: 1800000
connection-timeout: 30000
connection-test-query: SELECT 1
server:
port: 8080
5、服务器安全配置
创建一个类继承 WebSecurityConfigurerAdapter
并添加相关注解
@Configuration
@EnableWebSecurity
//全局方法拦截
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
@Bean
public BCryptPasswordEncoder passwordEncoder() {
// 配置默认的加密方式
return new BCryptPasswordEncoder();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// 在内存中创建用户,用于登录
auth.inMemoryAuthentication()
.withUser("user").password(passwordEncoder().encode("123456")).roles("USER")
.and()
.withUser("admin").password(passwordEncoder().encode("admin888")).roles("ADMIN");
}
}
6、配置认证服务器
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfigurerAdapter extends org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter {
@Bean
//重写DataSource需要加入此注解,表示以此配置为准
@Primary
@ConfigurationProperties(prefix="spring.datasource")
public DataSource dataSource(){
return DataSourceBuilder.create().build();
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
//token存储到数据库中
endpoints.tokenStore(tokenStore());
}
@Bean
public TokenStore tokenStore(){
// 基于 JDBC 实现,令牌保存到数据库
return new JdbcTokenStore(dataSource());
}
@Bean
public ClientDetailsService JdbcClientDetailsService(){
//从数据库中读取client_id,client_secret
return new JdbcClientDetailsService(dataSource());
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
//客户端配置,配置信息在数据库中,使用到ClientDetailsService
clients.withClientDetails(JdbcClientDetailsService());
}
}
测试
获取授权码
启动服务
- 通过浏览器访问
http://localhost:8080/oauth/authorize?client_id=client&response_type=code
- 第一次访问会跳转到登录页面,输入用户的账号密码
- 成功后会询问用户是否授权客户端,点击同意
- 选择授权后会跳转到服务器回调地址,浏览器地址上还会包含一个授权码(
code=1JuO6V
),浏览器地址栏会显示如下地址:
https://www.baidu.com/?code=1JuO6V
向服务器申请令牌
使用Postman请求