Skip to content

Commit d3ca41e

Browse files
committed
基于Spring Security Oauth2的SSO单点登录+JWT权限控制实践
1 parent a811fe5 commit d3ca41e

File tree

17 files changed

+450
-0
lines changed

17 files changed

+450
-0
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns="http://maven.apache.org/POM/4.0.0"
3+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5+
<parent>
6+
<artifactId>springbt_sso_jwt</artifactId>
7+
<groupId>cn.codesheep</groupId>
8+
<version>1.0-SNAPSHOT</version>
9+
</parent>
10+
<modelVersion>4.0.0</modelVersion>
11+
12+
<artifactId>codesheep-client1</artifactId>
13+
14+
<dependencies>
15+
<dependency>
16+
<groupId>org.springframework.cloud</groupId>
17+
<artifactId>spring-cloud-starter-oauth2</artifactId>
18+
<!--<version>2.0.1.RELEASE</version>-->
19+
</dependency>
20+
</dependencies>
21+
22+
</project>
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package cn.codesheep;
2+
3+
import org.springframework.boot.SpringApplication;
4+
import org.springframework.boot.autoconfigure.SpringBootApplication;
5+
6+
@SpringBootApplication
7+
public class Client1Application {
8+
9+
public static void main(String[] args) {
10+
SpringApplication.run(Client1Application.class, args);
11+
}
12+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package cn.codesheep.config;
2+
3+
4+
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
5+
import org.springframework.context.annotation.Configuration;
6+
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
7+
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
8+
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
9+
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
10+
11+
@Configuration
12+
@EnableWebSecurity
13+
@EnableGlobalMethodSecurity(prePostEnabled = true)
14+
@EnableOAuth2Sso
15+
public class ClientWebsecurityConfigurer extends WebSecurityConfigurerAdapter {
16+
17+
@Override
18+
public void configure(HttpSecurity http) throws Exception {
19+
http.antMatcher("/**").authorizeRequests()
20+
.anyRequest().authenticated();
21+
}
22+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package cn.codesheep.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.RestController;
6+
7+
@RestController
8+
public class TestController {
9+
10+
@GetMapping("/normal")
11+
@PreAuthorize("hasAuthority('ROLE_NORMAL')")
12+
public String normal( ) {
13+
return "normal permission test success !!!";
14+
}
15+
16+
@GetMapping("/medium")
17+
@PreAuthorize("hasAuthority('ROLE_MEDIUM')")
18+
public String medium() {
19+
return "medium permission test success !!!";
20+
}
21+
22+
@GetMapping("/admin")
23+
@PreAuthorize("hasAuthority('ROLE_ADMIN')")
24+
public String admin() {
25+
return "admin permission test success !!!";
26+
}
27+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
auth-server: http://localhost:8085/uac
2+
server:
3+
port: 8086
4+
5+
security:
6+
oauth2:
7+
client:
8+
client-id: sheep1
9+
client-secret: 123456
10+
user-authorization-uri: ${auth-server}/oauth/authorize
11+
access-token-uri: ${auth-server}/oauth/token
12+
resource:
13+
jwt:
14+
key-uri: ${auth-server}/oauth/token_key
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns="http://maven.apache.org/POM/4.0.0"
3+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5+
<parent>
6+
<artifactId>springbt_sso_jwt</artifactId>
7+
<groupId>cn.codesheep</groupId>
8+
<version>1.0-SNAPSHOT</version>
9+
</parent>
10+
<modelVersion>4.0.0</modelVersion>
11+
12+
<artifactId>codesheep-client2</artifactId>
13+
14+
<dependencies>
15+
<dependency>
16+
<groupId>org.springframework.cloud</groupId>
17+
<artifactId>spring-cloud-starter-oauth2</artifactId>
18+
<!--<version>2.0.1.RELEASE</version>-->
19+
</dependency>
20+
</dependencies>
21+
22+
</project>
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package cn.codesheep;
2+
3+
import org.springframework.boot.SpringApplication;
4+
import org.springframework.boot.autoconfigure.SpringBootApplication;
5+
6+
@SpringBootApplication
7+
public class Client2Application {
8+
9+
public static void main(String[] args) {
10+
SpringApplication.run(Client2Application.class, args);
11+
}
12+
}
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
package cn.codesheep.config;
2+
3+
4+
import org.springframework.boot.autoconfigure.security.oauth2.client.EnableOAuth2Sso;
5+
import org.springframework.context.annotation.Configuration;
6+
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
7+
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
8+
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
9+
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
10+
11+
@Configuration
12+
@EnableWebSecurity
13+
@EnableGlobalMethodSecurity(prePostEnabled = true)
14+
@EnableOAuth2Sso
15+
public class ClientWebsecurityConfigurer extends WebSecurityConfigurerAdapter {
16+
17+
@Override
18+
public void configure(HttpSecurity http) throws Exception {
19+
http.antMatcher("/**").authorizeRequests()
20+
.anyRequest().authenticated();
21+
}
22+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package cn.codesheep.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.RestController;
6+
7+
@RestController
8+
public class TestController {
9+
10+
@GetMapping("/normal")
11+
@PreAuthorize("hasAuthority('ROLE_NORMAL')")
12+
public String normal( ) {
13+
return "normal permission test success !!!";
14+
}
15+
16+
@GetMapping("/medium")
17+
@PreAuthorize("hasAuthority('ROLE_MEDIUM')")
18+
public String medium() {
19+
return "medium permission test success !!!";
20+
}
21+
22+
@GetMapping("/admin")
23+
@PreAuthorize("hasAuthority('ROLE_ADMIN')")
24+
public String admin() {
25+
return "admin permission test success !!!";
26+
}
27+
}
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
auth-server: http://localhost:8085/uac
2+
server:
3+
port: 8087
4+
5+
security:
6+
oauth2:
7+
client:
8+
client-id: sheep2
9+
client-secret: 123456
10+
user-authorization-uri: ${auth-server}/oauth/authorize
11+
access-token-uri: ${auth-server}/oauth/token
12+
resource:
13+
jwt:
14+
key-uri: ${auth-server}/oauth/token_key
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns="http://maven.apache.org/POM/4.0.0"
3+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
5+
<parent>
6+
<artifactId>springbt_sso_jwt</artifactId>
7+
<groupId>cn.codesheep</groupId>
8+
<version>1.0-SNAPSHOT</version>
9+
</parent>
10+
<modelVersion>4.0.0</modelVersion>
11+
12+
<artifactId>codesheep-server</artifactId>
13+
<build>
14+
<plugins>
15+
<plugin>
16+
<groupId>org.apache.maven.plugins</groupId>
17+
<artifactId>maven-compiler-plugin</artifactId>
18+
<configuration>
19+
<source>6</source>
20+
<target>6</target>
21+
</configuration>
22+
</plugin>
23+
</plugins>
24+
</build>
25+
26+
<dependencies>
27+
<dependency>
28+
<groupId>org.springframework.cloud</groupId>
29+
<artifactId>spring-cloud-starter-oauth2</artifactId>
30+
</dependency>
31+
</dependencies>
32+
33+
</project>
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package cn.codesheep;
2+
3+
import org.springframework.boot.SpringApplication;
4+
import org.springframework.boot.autoconfigure.SpringBootApplication;
5+
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
6+
7+
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
8+
public class ServerApplication {
9+
10+
public static void main(String[] args) {
11+
SpringApplication.run(ServerApplication.class, args);
12+
}
13+
}
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
package cn.codesheep.config;
2+
3+
import org.springframework.context.annotation.Bean;
4+
import org.springframework.context.annotation.Configuration;
5+
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
6+
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
7+
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
8+
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
9+
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
10+
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
11+
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
12+
import org.springframework.security.oauth2.provider.token.TokenStore;
13+
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
14+
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
15+
import java.util.concurrent.TimeUnit;
16+
17+
18+
@Configuration
19+
@EnableAuthorizationServer
20+
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
21+
22+
@Override
23+
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
24+
25+
// 定义了两个客户端应用的通行证
26+
clients.inMemory()
27+
.withClient("sheep1")
28+
.secret(new BCryptPasswordEncoder().encode("123456"))
29+
.authorizedGrantTypes("authorization_code", "refresh_token")
30+
.scopes("all")
31+
.autoApprove(false)
32+
.and()
33+
.withClient("sheep2")
34+
.secret(new BCryptPasswordEncoder().encode("123456"))
35+
.authorizedGrantTypes("authorization_code", "refresh_token")
36+
.scopes("all")
37+
.autoApprove(false);
38+
}
39+
40+
@Override
41+
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
42+
43+
endpoints.tokenStore(jwtTokenStore()).accessTokenConverter(jwtAccessTokenConverter());
44+
DefaultTokenServices tokenServices = (DefaultTokenServices) endpoints.getDefaultAuthorizationServerTokenServices();
45+
tokenServices.setTokenStore(endpoints.getTokenStore());
46+
tokenServices.setSupportRefreshToken(true);
47+
tokenServices.setClientDetailsService(endpoints.getClientDetailsService());
48+
tokenServices.setTokenEnhancer(endpoints.getTokenEnhancer());
49+
tokenServices.setAccessTokenValiditySeconds((int) TimeUnit.DAYS.toSeconds(1)); // 一天有效期
50+
endpoints.tokenServices(tokenServices);
51+
}
52+
53+
@Override
54+
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
55+
security.tokenKeyAccess("isAuthenticated()");
56+
}
57+
58+
@Bean
59+
public TokenStore jwtTokenStore() {
60+
return new JwtTokenStore(jwtAccessTokenConverter());
61+
}
62+
63+
@Bean
64+
public JwtAccessTokenConverter jwtAccessTokenConverter(){
65+
JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
66+
converter.setSigningKey("testKey");
67+
return converter;
68+
}
69+
70+
}
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package cn.codesheep.config;
2+
3+
import org.springframework.beans.factory.annotation.Autowired;
4+
import org.springframework.context.annotation.Bean;
5+
import org.springframework.context.annotation.Configuration;
6+
import org.springframework.security.authentication.AuthenticationManager;
7+
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
8+
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
9+
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
10+
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
11+
import org.springframework.security.core.userdetails.UserDetailsService;
12+
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
13+
import org.springframework.security.crypto.password.PasswordEncoder;
14+
15+
@Configuration
16+
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
17+
18+
@Override
19+
@Bean
20+
public AuthenticationManager authenticationManager() throws Exception {
21+
return super.authenticationManager();
22+
}
23+
24+
@Autowired
25+
private UserDetailsService userDetailsService;
26+
27+
@Bean
28+
public PasswordEncoder passwordEncoder() {
29+
return new BCryptPasswordEncoder();
30+
}
31+
32+
@Bean
33+
public DaoAuthenticationProvider authenticationProvider() {
34+
DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
35+
authenticationProvider.setUserDetailsService(userDetailsService);
36+
authenticationProvider.setPasswordEncoder(passwordEncoder());
37+
authenticationProvider.setHideUserNotFoundExceptions(false);
38+
return authenticationProvider;
39+
}
40+
41+
@Override
42+
protected void configure(HttpSecurity http) throws Exception {
43+
44+
http
45+
.requestMatchers().antMatchers("/oauth/**","/login/**","/logout/**")
46+
.and()
47+
.authorizeRequests()
48+
.antMatchers("/oauth/**").authenticated()
49+
.and()
50+
.formLogin().permitAll();
51+
}
52+
53+
@Override
54+
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
55+
auth.authenticationProvider(authenticationProvider());
56+
}
57+
58+
}
59+

0 commit comments

Comments
 (0)