Skip to content

Commit 0fb268b

Browse files
committed
第十五篇 : Spring Boot Security 整合 OAuth2 设计安全API接口服务
1 parent a6254dd commit 0fb268b

25 files changed

Lines changed: 1029 additions & 0 deletions
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
HELP.md
2+
/target/
3+
!.mvn/wrapper/maven-wrapper.jar
4+
5+
### STS ###
6+
.apt_generated
7+
.classpath
8+
.factorypath
9+
.project
10+
.settings
11+
.springBeans
12+
.sts4-cache
13+
14+
### IntelliJ IDEA ###
15+
.idea
16+
*.iws
17+
*.iml
18+
*.ipr
19+
20+
### NetBeans ###
21+
/nbproject/private/
22+
/nbbuild/
23+
/dist/
24+
/nbdist/
25+
/.nb-gradle/
26+
/build/
Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
/*
2+
Licensed to the Apache Software Foundation (ASF) under one
3+
or more contributor license agreements. See the NOTICE file
4+
distributed with this work for additional information
5+
regarding copyright ownership. The ASF licenses this file
6+
to you under the Apache License, Version 2.0 (the
7+
"License"); you may not use this file except in compliance
8+
with the License. You may obtain a copy of the License at
9+
10+
http://www.apache.org/licenses/LICENSE-2.0
11+
12+
Unless required by applicable law or agreed to in writing,
13+
software distributed under the License is distributed on an
14+
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15+
KIND, either express or implied. See the License for the
16+
specific language governing permissions and limitations
17+
under the License.
18+
*/
19+
20+
import java.io.File;
21+
import java.io.FileInputStream;
22+
import java.io.FileOutputStream;
23+
import java.io.IOException;
24+
import java.net.URL;
25+
import java.nio.channels.Channels;
26+
import java.nio.channels.ReadableByteChannel;
27+
import java.util.Properties;
28+
29+
public class MavenWrapperDownloader {
30+
31+
/**
32+
* Default URL to download the maven-wrapper.jar from, if no 'downloadUrl' is provided.
33+
*/
34+
private static final String DEFAULT_DOWNLOAD_URL =
35+
"https://repo.maven.apache.org/maven2/io/takari/maven-wrapper/0.4.2/maven-wrapper-0.4.2.jar";
36+
37+
/**
38+
* Path to the maven-wrapper.properties file, which might contain a downloadUrl property to
39+
* use instead of the default one.
40+
*/
41+
private static final String MAVEN_WRAPPER_PROPERTIES_PATH =
42+
".mvn/wrapper/maven-wrapper.properties";
43+
44+
/**
45+
* Path where the maven-wrapper.jar will be saved to.
46+
*/
47+
private static final String MAVEN_WRAPPER_JAR_PATH =
48+
".mvn/wrapper/maven-wrapper.jar";
49+
50+
/**
51+
* Name of the property which should be used to override the default download url for the wrapper.
52+
*/
53+
private static final String PROPERTY_NAME_WRAPPER_URL = "wrapperUrl";
54+
55+
public static void main(String args[]) {
56+
System.out.println( "- Downloader started" );
57+
File baseDirectory = new File( args[0] );
58+
System.out.println( "- Using base directory: " + baseDirectory.getAbsolutePath() );
59+
60+
// If the maven-wrapper.properties exists, read it and check if it contains a custom
61+
// wrapperUrl parameter.
62+
File mavenWrapperPropertyFile = new File( baseDirectory, MAVEN_WRAPPER_PROPERTIES_PATH );
63+
String url = DEFAULT_DOWNLOAD_URL;
64+
if (mavenWrapperPropertyFile.exists()) {
65+
FileInputStream mavenWrapperPropertyFileInputStream = null;
66+
try {
67+
mavenWrapperPropertyFileInputStream = new FileInputStream( mavenWrapperPropertyFile );
68+
Properties mavenWrapperProperties = new Properties();
69+
mavenWrapperProperties.load( mavenWrapperPropertyFileInputStream );
70+
url = mavenWrapperProperties.getProperty( PROPERTY_NAME_WRAPPER_URL, url );
71+
} catch (IOException e) {
72+
System.out.println( "- ERROR loading '" + MAVEN_WRAPPER_PROPERTIES_PATH + "'" );
73+
} finally {
74+
try {
75+
if (mavenWrapperPropertyFileInputStream != null) {
76+
mavenWrapperPropertyFileInputStream.close();
77+
}
78+
} catch (IOException e) {
79+
// Ignore ...
80+
}
81+
}
82+
}
83+
System.out.println( "- Downloading from: : " + url );
84+
85+
File outputFile = new File( baseDirectory.getAbsolutePath(), MAVEN_WRAPPER_JAR_PATH );
86+
if (!outputFile.getParentFile().exists()) {
87+
if (!outputFile.getParentFile().mkdirs()) {
88+
System.out.println(
89+
"- ERROR creating output direcrory '" + outputFile.getParentFile().getAbsolutePath() + "'" );
90+
}
91+
}
92+
System.out.println( "- Downloading to: " + outputFile.getAbsolutePath() );
93+
try {
94+
downloadFileFromURL( url, outputFile );
95+
System.out.println( "Done" );
96+
System.exit( 0 );
97+
} catch (Throwable e) {
98+
System.out.println( "- Error downloading" );
99+
e.printStackTrace();
100+
System.exit( 1 );
101+
}
102+
}
103+
104+
private static void downloadFileFromURL(String urlString, File destination) throws Exception {
105+
URL website = new URL( urlString );
106+
ReadableByteChannel rbc;
107+
rbc = Channels.newChannel( website.openStream() );
108+
FileOutputStream fos = new FileOutputStream( destination );
109+
fos.getChannel().transferFrom( rbc, 0, Long.MAX_VALUE );
110+
fos.close();
111+
rbc.close();
112+
}
113+
114+
}
47.2 KB
Binary file not shown.
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.6.0/apache-maven-3.6.0-bin.zip

springboot-security-oauth2/pom.xml

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
4+
<modelVersion>4.0.0</modelVersion>
5+
<parent>
6+
<groupId>org.springframework.boot</groupId>
7+
<artifactId>spring-boot-starter-parent</artifactId>
8+
<version>2.1.3.RELEASE</version>
9+
<relativePath/> <!-- lookup parent from repository -->
10+
</parent>
11+
<groupId>com.gf</groupId>
12+
<artifactId>springboot-security</artifactId>
13+
<version>0.0.1-SNAPSHOT</version>
14+
<name>springboot-security</name>
15+
<description>Demo project for Spring Boot</description>
16+
17+
<properties>
18+
<java.version>1.8</java.version>
19+
</properties>
20+
21+
<dependencies>
22+
<dependency>
23+
<groupId>org.springframework.boot</groupId>
24+
<artifactId>spring-boot-starter-security</artifactId>
25+
</dependency>
26+
<dependency>
27+
<groupId>org.springframework.boot</groupId>
28+
<artifactId>spring-boot-starter-thymeleaf</artifactId>
29+
</dependency>
30+
<dependency>
31+
<groupId>org.springframework.boot</groupId>
32+
<artifactId>spring-boot-starter-oauth2-client</artifactId>
33+
</dependency>
34+
<dependency>
35+
<groupId>org.springframework.boot</groupId>
36+
<artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
37+
</dependency>
38+
<dependency>
39+
<groupId>org.springframework.security.oauth.boot</groupId>
40+
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
41+
<version>2.1.3.RELEASE</version>
42+
</dependency>
43+
<dependency>
44+
<groupId>org.springframework.boot</groupId>
45+
<artifactId>spring-boot-starter-web</artifactId>
46+
</dependency>
47+
<dependency>
48+
<groupId>org.mybatis.spring.boot</groupId>
49+
<artifactId>mybatis-spring-boot-starter</artifactId>
50+
<version>1.3.2</version>
51+
</dependency>
52+
<dependency>
53+
<groupId>mysql</groupId>
54+
<artifactId>mysql-connector-java</artifactId>
55+
<scope>runtime</scope>
56+
</dependency>
57+
58+
<dependency>
59+
<groupId>org.projectlombok</groupId>
60+
<artifactId>lombok</artifactId>
61+
<optional>true</optional>
62+
</dependency>
63+
<dependency>
64+
<groupId>org.springframework.boot</groupId>
65+
<artifactId>spring-boot-starter-test</artifactId>
66+
<scope>test</scope>
67+
</dependency>
68+
<dependency>
69+
<groupId>org.springframework.security</groupId>
70+
<artifactId>spring-security-test</artifactId>
71+
<scope>test</scope>
72+
</dependency>
73+
</dependencies>
74+
75+
<build>
76+
<plugins>
77+
<plugin>
78+
<groupId>org.springframework.boot</groupId>
79+
<artifactId>spring-boot-maven-plugin</artifactId>
80+
</plugin>
81+
</plugins>
82+
</build>
83+
84+
</project>
Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package com.gf;
2+
3+
import org.springframework.boot.SpringApplication;
4+
import org.springframework.boot.autoconfigure.SpringBootApplication;
5+
6+
@SpringBootApplication
7+
public class SpringbootSecurityApplication {
8+
9+
public static void main(String[] args) {
10+
SpringApplication.run( SpringbootSecurityApplication.class, args );
11+
}
12+
13+
}
Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
package com.gf.config;
2+
3+
import com.gf.service.MyUserDetailsService;
4+
import org.springframework.beans.factory.annotation.Autowired;
5+
import org.springframework.context.annotation.Bean;
6+
import org.springframework.context.annotation.Configuration;
7+
import org.springframework.http.HttpHeaders;
8+
import org.springframework.security.authentication.AuthenticationManager;
9+
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
10+
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
11+
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
12+
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
13+
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
14+
import org.springframework.security.oauth2.provider.error.WebResponseExceptionTranslator;
15+
import org.springframework.security.oauth2.provider.token.TokenStore;
16+
import org.springframework.security.oauth2.provider.token.store.JdbcTokenStore;
17+
import org.springframework.web.cors.CorsConfiguration;
18+
import org.springframework.web.cors.CorsConfigurationSource;
19+
import org.springframework.web.filter.CorsFilter;
20+
21+
import javax.servlet.http.HttpServletRequest;
22+
import javax.sql.DataSource;
23+
24+
/**
25+
* 认证服务器配置
26+
*/
27+
@Configuration
28+
@EnableAuthorizationServer
29+
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
30+
31+
32+
/**
33+
* 注入权限验证控制器 来支持 password grant type
34+
*/
35+
@Autowired
36+
private AuthenticationManager authenticationManager;
37+
38+
/**
39+
* 注入userDetailsService,开启refresh_token需要用到
40+
*/
41+
@Autowired
42+
private MyUserDetailsService userDetailsService;
43+
44+
/**
45+
* 数据源
46+
*/
47+
@Autowired
48+
private DataSource dataSource;
49+
50+
/**
51+
* 设置保存token的方式,一共有五种,这里采用数据库的方式
52+
*/
53+
@Autowired
54+
private TokenStore tokenStore;
55+
56+
@Autowired
57+
private WebResponseExceptionTranslator webResponseExceptionTranslator;
58+
59+
@Bean
60+
public TokenStore tokenStore() {
61+
return new JdbcTokenStore( dataSource );
62+
}
63+
64+
@Override
65+
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
66+
/**
67+
* 配置oauth2服务跨域
68+
*/
69+
CorsConfigurationSource source = new CorsConfigurationSource() {
70+
@Override
71+
public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
72+
CorsConfiguration corsConfiguration = new CorsConfiguration();
73+
corsConfiguration.addAllowedHeader("*");
74+
corsConfiguration.addAllowedOrigin(request.getHeader( HttpHeaders.ORIGIN));
75+
corsConfiguration.addAllowedMethod("*");
76+
corsConfiguration.setAllowCredentials(true);
77+
corsConfiguration.setMaxAge(3600L);
78+
return corsConfiguration;
79+
}
80+
};
81+
82+
security.tokenKeyAccess("permitAll()")
83+
.checkTokenAccess("permitAll()")
84+
.allowFormAuthenticationForClients()
85+
.addTokenEndpointAuthenticationFilter(new CorsFilter(source));
86+
}
87+
88+
@Override
89+
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
90+
clients.jdbc(dataSource);
91+
}
92+
93+
@Override
94+
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
95+
//开启密码授权类型
96+
endpoints.authenticationManager(authenticationManager);
97+
//配置token存储方式
98+
endpoints.tokenStore(tokenStore);
99+
//自定义登录或者鉴权失败时的返回信息
100+
endpoints.exceptionTranslator(webResponseExceptionTranslator);
101+
//要使用refresh_token的话,需要额外配置userDetailsService
102+
endpoints.userDetailsService( userDetailsService );
103+
104+
}
105+
106+
107+
}

0 commit comments

Comments
 (0)