Skip to content

Commit ac113de

Browse files
author
YunaiV
committed
增加 SSO 示例
1 parent 0eff761 commit ac113de

File tree

12 files changed

+182
-24
lines changed

12 files changed

+182
-24
lines changed

lab-68/lab-68-demo21-authorization-server-on-sso/pom.xml

+12
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,18 @@
5050
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
5151
<version>${spring.boot.version}</version>
5252
</dependency>
53+
54+
<!-- 实现对数据库连接池的自动化配置 -->
55+
<dependency>
56+
<groupId>org.springframework.boot</groupId>
57+
<artifactId>spring-boot-starter-jdbc</artifactId>
58+
</dependency>
59+
<dependency> <!-- 本示例,我们使用 MySQL -->
60+
<groupId>mysql</groupId>
61+
<artifactId>mysql-connector-java</artifactId>
62+
<version>5.1.48</version>
63+
</dependency>
64+
5365
</dependencies>
5466

5567
</project>
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,20 @@
11
package cn.iocoder.springboot.lab68.authorizationserverdemo.config;
22

33
import org.springframework.beans.factory.annotation.Autowired;
4+
import org.springframework.context.annotation.Bean;
45
import org.springframework.context.annotation.Configuration;
56
import org.springframework.security.authentication.AuthenticationManager;
67
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
78
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
89
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
910
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
1011
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
12+
import org.springframework.security.oauth2.provider.ClientDetailsService;
13+
import org.springframework.security.oauth2.provider.client.JdbcClientDetailsService;
14+
import org.springframework.security.oauth2.provider.token.TokenStore;
15+
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
16+
17+
import javax.sql.DataSource;
1118

1219
/**
1320
* 授权服务器配置
@@ -22,27 +29,40 @@ public class OAuth2AuthorizationServerConfig extends AuthorizationServerConfigur
2229
@Autowired
2330
private AuthenticationManager authenticationManager;
2431

32+
/**
33+
* 数据源 DataSource
34+
*/
35+
@Autowired
36+
private DataSource dataSource;
37+
38+
@Bean
39+
public TokenStore jdbcTokenStore() {
40+
return new JdbcTokenStore(dataSource);
41+
}
42+
2543
@Override
2644
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
27-
endpoints.authenticationManager(authenticationManager);
45+
endpoints.authenticationManager(authenticationManager)
46+
.tokenStore(jdbcTokenStore());
2847
}
2948

3049
@Override
3150
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
32-
oauthServer.checkTokenAccess("isAuthenticated()")
33-
// .tokenKeyAccess("permitAll()")
34-
;
51+
oauthServer.checkTokenAccess("isAuthenticated()");
52+
// oauthServer.tokenKeyAccess("isAuthenticated()")
53+
// .checkTokenAccess("isAuthenticated()");
54+
// oauthServer.tokenKeyAccess("permitAll()")
55+
// .checkTokenAccess("permitAll()");
56+
}
57+
58+
@Bean
59+
public ClientDetailsService jdbcClientDetailsService() {
60+
return new JdbcClientDetailsService(dataSource);
3561
}
3662

3763
@Override
3864
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
39-
clients.inMemory()
40-
.withClient("clientapp").secret("112233") // Client 账号、密码。
41-
.authorizedGrantTypes("authorization_code") // 授权码模式
42-
.redirectUris("http://127.0.0.1:9090/login") // 配置回调地址,选填。
43-
.scopes("read_userinfo", "read_contacts") // 可授权的 Scope
44-
// .and().withClient() // 可以继续配置新的 Client
45-
;
65+
clients.withClientDetails(jdbcClientDetailsService());
4666
}
4767

4868
}

lab-68/lab-68-demo21-authorization-server-on-sso/src/main/java/cn/iocoder/springboot/lab68/authorizationserverdemo/config/SecurityConfig.java

+11-7
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package cn.iocoder.springboot.lab68.authorizationserverdemo.config;
22

3+
import org.springframework.beans.factory.annotation.Autowired;
34
import org.springframework.context.annotation.Bean;
45
import org.springframework.context.annotation.Configuration;
56
import org.springframework.security.authentication.AuthenticationManager;
@@ -9,10 +10,18 @@
910
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
1011
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
1112

13+
import javax.sql.DataSource;
14+
1215
@Configuration
1316
@EnableWebSecurity
1417
public class SecurityConfig extends WebSecurityConfigurerAdapter {
1518

19+
/**
20+
* 数据源 DataSource
21+
*/
22+
@Autowired
23+
private DataSource dataSource;
24+
1625
@Override
1726
@Bean(name = BeanIds.AUTHENTICATION_MANAGER)
1827
public AuthenticationManager authenticationManagerBean() throws Exception {
@@ -26,13 +35,8 @@ public static NoOpPasswordEncoder passwordEncoder() {
2635

2736
@Override
2837
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
29-
auth.
30-
// 使用内存中的 InMemoryUserDetailsManager
31-
inMemoryAuthentication()
32-
// 不使用 PasswordEncoder 密码编码器
33-
.passwordEncoder(passwordEncoder())
34-
// 配置 yunai 用户
35-
.withUser("yunai").password("1024").roles("USER");
38+
auth.jdbcAuthentication()
39+
.dataSource(dataSource);
3640
}
3741

3842
// @Override
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
spring:
2+
# datasource 数据源配置内容,对应 DataSourceProperties 配置属性类
3+
datasource:
4+
url: jdbc:mysql://127.0.0.1:43063/demo-68-authorization-server-sso?useSSL=false&useUnicode=true&characterEncoding=UTF-8
5+
driver-class-name: com.mysql.jdbc.Driver
6+
username: root # 数据库账号
7+
password: 123456 # 数据库密码
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
INSERT INTO oauth_client_details
2+
(client_id, client_secret, scope, authorized_grant_types,
3+
web_server_redirect_uri, authorities, access_token_validity,
4+
refresh_token_validity, additional_information, autoapprove)
5+
VALUES
6+
('clientapp', '112233', 'read_userinfo,read_contacts',
7+
'password,refresh_token', null, null, 3600, 864000, null, true);
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
drop table if exists oauth_client_details;
2+
create table oauth_client_details (
3+
client_id VARCHAR(255) PRIMARY KEY,
4+
resource_ids VARCHAR(255),
5+
client_secret VARCHAR(255),
6+
scope VARCHAR(255),
7+
authorized_grant_types VARCHAR(255),
8+
web_server_redirect_uri VARCHAR(255),
9+
authorities VARCHAR(255),
10+
access_token_validity INTEGER,
11+
refresh_token_validity INTEGER,
12+
additional_information VARCHAR(4096),
13+
autoapprove VARCHAR(255)
14+
);
15+
16+
create table if not exists oauth_client_token (
17+
token_id VARCHAR(255),
18+
token LONG VARBINARY,
19+
authentication_id VARCHAR(255) PRIMARY KEY,
20+
user_name VARCHAR(255),
21+
client_id VARCHAR(255)
22+
);
23+
24+
create table if not exists oauth_access_token (
25+
token_id VARCHAR(255),
26+
token LONG VARBINARY,
27+
authentication_id VARCHAR(255) PRIMARY KEY,
28+
user_name VARCHAR(255),
29+
client_id VARCHAR(255),
30+
authentication LONG VARBINARY,
31+
refresh_token VARCHAR(255)
32+
);
33+
34+
create table if not exists oauth_refresh_token (
35+
token_id VARCHAR(255),
36+
token LONG VARBINARY,
37+
authentication LONG VARBINARY
38+
);
39+
40+
create table if not exists oauth_code (
41+
code VARCHAR(255), authentication LONG VARBINARY
42+
);
43+
44+
create table if not exists oauth_approvals (
45+
userId VARCHAR(255),
46+
clientId VARCHAR(255),
47+
scope VARCHAR(255),
48+
status VARCHAR(10),
49+
expiresAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
50+
lastModifiedAt TIMESTAMP DEFAULT CURRENT_TIMESTAMP
51+
);
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
INSERT INTO `authorities` VALUES ('yunai', 'ROLE_USER');
2+
3+
INSERT INTO `users` VALUES ('yunai', '112233', '1');
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
DROP TABLE IF EXISTS `authorities`;
2+
CREATE TABLE `authorities` (
3+
`username` varchar(50) NOT NULL,
4+
`authority` varchar(50) NOT NULL,
5+
UNIQUE KEY `ix_auth_username` (`username`,`authority`)
6+
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
7+
8+
DROP TABLE IF EXISTS `users`;
9+
CREATE TABLE `users` (
10+
`username` varchar(50) NOT NULL,
11+
`password` varchar(500) NOT NULL,
12+
`enabled` tinyint(1) NOT NULL,
13+
PRIMARY KEY (`username`)
14+
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package cn.iocoder.springboot.lab68.resourceserverdemo.config;
2+
3+
import org.springframework.context.annotation.Configuration;
4+
import org.springframework.core.annotation.Order;
5+
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
6+
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
7+
8+
@Configuration
9+
@EnableGlobalMethodSecurity(prePostEnabled = true)
10+
@Order(101)
11+
public class SecurityConfig extends WebSecurityConfigurerAdapter {
12+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package cn.iocoder.springboot.lab68.resourceserverdemo.controller;
2+
3+
import org.springframework.security.access.prepost.PreAuthorize;
4+
import org.springframework.web.bind.annotation.GetMapping;
5+
import org.springframework.web.bind.annotation.RequestMapping;
6+
import org.springframework.web.bind.annotation.RestController;
7+
8+
/**
9+
* 示例 Controller
10+
*/
11+
@RestController
12+
@RequestMapping("/demo")
13+
public class DemoController {
14+
15+
@GetMapping("/admin-list")
16+
@PreAuthorize("hasAuthority('admin')")
17+
public String adminList() {
18+
return "管理员列表";
19+
}
20+
21+
@GetMapping("/user-list")
22+
@PreAuthorize("hasAuthority('user')")
23+
public String userList() {
24+
return "用户列表";
25+
}
26+
27+
}

lab-68/lab-68-demo21-resource-server-on-sso/src/main/java/cn/iocoder/springboot/lab68/resourceserverdemo/controller/UserController.java

+3-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
package cn.iocoder.springboot.lab68.resourceserverdemo.controller;
22

3+
import org.springframework.security.core.Authentication;
34
import org.springframework.web.bind.annotation.RequestMapping;
45
import org.springframework.web.bind.annotation.RestController;
56

@@ -11,8 +12,8 @@
1112
public class UserController {
1213

1314
@RequestMapping("/info")
14-
public String hello() {
15-
return "world";
15+
public Authentication info(Authentication authentication) {
16+
return authentication;
1617
}
1718

1819
}

lab-68/lab-68-demo21-resource-server-on-sso/src/main/resources/application.yml

+4-4
Original file line numberDiff line numberDiff line change
@@ -3,16 +3,16 @@ server:
33
servlet:
44
session:
55
cookie:
6-
name: OAUTH2-CLIENT-SESSIONID
6+
name: SSO-SESSIONID # 自定义 Session 的 Cookie 名字,防止冲突。冲突后,会导致 SSO 登陆失败。
77

88
security:
99
oauth2:
1010
# OAuth2 Client 配置,对应 OAuth2ClientProperties 类
1111
client:
1212
client-id: clientapp
1313
client-secret: 112233
14-
user-authorization-uri: http://127.0.0.1:8080/oauth/authorize #
15-
access-token-uri: http://127.0.0.1:8080/oauth/token
14+
user-authorization-uri: http://127.0.0.1:8080/oauth/authorize # 获取用户的授权码地址
15+
access-token-uri: http://127.0.0.1:8080/oauth/token # 获取访问令牌的地址
1616
# OAuth2 Resource 配置,对应 ResourceServerProperties 类
1717
resource:
18-
token-info-uri: http://127.0.0.1:8080/oauth/check_token # 获得 Token 信息的 URL
18+
token-info-uri: http://127.0.0.1:8080/oauth/check_token # 校验访问令牌是否有效的地址

0 commit comments

Comments
 (0)