Skip to content

Commit de16919

Browse files
committed
第十六篇 : Spring Boot Security 整合 JWT 实现 无状态的分布式API接口
1 parent 3feff03 commit de16919

24 files changed

Lines changed: 1003 additions & 0 deletions

springboot-jwt/.gitignore

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
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/
27+
28+
### VS Code ###
29+
.vscode/
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+
https://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-jwt/pom.xml

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
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-jwt</artifactId>
13+
<version>0.0.1-SNAPSHOT</version>
14+
<name>springboot-jwt</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-web</artifactId>
25+
</dependency>
26+
<dependency>
27+
<groupId>org.springframework.boot</groupId>
28+
<artifactId>spring-boot-starter-security</artifactId>
29+
</dependency>
30+
<dependency>
31+
<groupId>io.jsonwebtoken</groupId>
32+
<artifactId>jjwt</artifactId>
33+
<version>0.9.0</version>
34+
</dependency>
35+
<dependency>
36+
<groupId>mysql</groupId>
37+
<artifactId>mysql-connector-java</artifactId>
38+
<scope>runtime</scope>
39+
</dependency>
40+
<dependency>
41+
<groupId>org.mybatis.spring.boot</groupId>
42+
<artifactId>mybatis-spring-boot-starter</artifactId>
43+
<version>2.0.0</version>
44+
</dependency>
45+
<dependency>
46+
<groupId>org.springframework.boot</groupId>
47+
<artifactId>spring-boot-starter-test</artifactId>
48+
<scope>test</scope>
49+
</dependency>
50+
<dependency>
51+
<groupId>org.springframework.security</groupId>
52+
<artifactId>spring-security-test</artifactId>
53+
<scope>test</scope>
54+
</dependency>
55+
</dependencies>
56+
57+
<build>
58+
<plugins>
59+
<plugin>
60+
<groupId>org.springframework.boot</groupId>
61+
<artifactId>spring-boot-maven-plugin</artifactId>
62+
</plugin>
63+
</plugins>
64+
</build>
65+
66+
</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 SpringbootJwtApplication {
8+
9+
public static void main(String[] args) {
10+
SpringApplication.run( SpringbootJwtApplication.class, args );
11+
}
12+
13+
}
Lines changed: 68 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,68 @@
1+
package com.gf.config;
2+
3+
4+
import org.slf4j.Logger;
5+
import org.slf4j.LoggerFactory;
6+
import org.springframework.security.access.AccessDecisionManager;
7+
import org.springframework.security.access.AccessDeniedException;
8+
import org.springframework.security.access.ConfigAttribute;
9+
import org.springframework.security.authentication.InsufficientAuthenticationException;
10+
import org.springframework.security.core.Authentication;
11+
import org.springframework.security.core.GrantedAuthority;
12+
import org.springframework.stereotype.Component;
13+
14+
import java.util.Collection;
15+
import java.util.Iterator;
16+
17+
/**
18+
* 决策器
19+
*/
20+
@Component
21+
public class MyAccessDecisionManager implements AccessDecisionManager {
22+
23+
private final static Logger logger = LoggerFactory.getLogger(MyAccessDecisionManager.class);
24+
25+
/**
26+
* 通过传递的参数来决定用户是否有访问对应受保护对象的权限
27+
*
28+
* @param authentication 包含了当前的用户信息,包括拥有的权限。这里的权限来源就是前面登录时UserDetailsService中设置的authorities。
29+
* @param object 就是FilterInvocation对象,可以得到request等web资源
30+
* @param configAttributes configAttributes是本次访问需要的权限
31+
*/
32+
@Override
33+
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
34+
if (null == configAttributes || 0 >= configAttributes.size()) {
35+
return;
36+
} else {
37+
String needRole;
38+
for(Iterator<ConfigAttribute> iter = configAttributes.iterator(); iter.hasNext(); ) {
39+
needRole = iter.next().getAttribute();
40+
41+
for(GrantedAuthority ga : authentication.getAuthorities()) {
42+
if(needRole.trim().equals(ga.getAuthority().trim())) {
43+
return;
44+
}
45+
}
46+
}
47+
throw new AccessDeniedException("当前访问没有权限");
48+
}
49+
50+
}
51+
52+
/**
53+
* 表示此AccessDecisionManager是否能够处理传递的ConfigAttribute呈现的授权请求
54+
*/
55+
@Override
56+
public boolean supports(ConfigAttribute configAttribute) {
57+
return true;
58+
}
59+
60+
/**
61+
* 表示当前AccessDecisionManager实现是否能够为指定的安全对象(方法调用或Web请求)提供访问控制决策
62+
*/
63+
@Override
64+
public boolean supports(Class<?> aClass) {
65+
return true;
66+
}
67+
68+
}
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
package com.gf.config;
2+
3+
4+
import org.springframework.beans.factory.annotation.Autowired;
5+
import org.springframework.security.access.SecurityMetadataSource;
6+
import org.springframework.security.access.intercept.AbstractSecurityInterceptor;
7+
import org.springframework.security.access.intercept.InterceptorStatusToken;
8+
import org.springframework.security.web.FilterInvocation;
9+
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
10+
import org.springframework.stereotype.Component;
11+
12+
import javax.servlet.Filter;
13+
import javax.servlet.FilterChain;
14+
import javax.servlet.ServletException;
15+
import javax.servlet.ServletRequest;
16+
import javax.servlet.ServletResponse;
17+
import java.io.IOException;
18+
19+
20+
@Component
21+
public class MyFilterSecurityInterceptor extends AbstractSecurityInterceptor implements Filter {
22+
23+
24+
@Autowired
25+
private FilterInvocationSecurityMetadataSource securityMetadataSource;
26+
27+
@Autowired
28+
public void setMyAccessDecisionManager(MyAccessDecisionManager myAccessDecisionManager) {
29+
super.setAccessDecisionManager(myAccessDecisionManager);
30+
}
31+
32+
33+
@Override
34+
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
35+
36+
FilterInvocation fi = new FilterInvocation(servletRequest, servletResponse, filterChain);
37+
invoke(fi);
38+
}
39+
40+
public void invoke(FilterInvocation fi) throws IOException, ServletException {
41+
42+
InterceptorStatusToken token = super.beforeInvocation(fi);
43+
try {
44+
//执行下一个拦截器
45+
fi.getChain().doFilter(fi.getRequest(), fi.getResponse());
46+
} finally {
47+
super.afterInvocation(token, null);
48+
}
49+
}
50+
51+
@Override
52+
public Class<?> getSecureObjectClass() {
53+
return FilterInvocation.class;
54+
}
55+
56+
@Override
57+
public SecurityMetadataSource obtainSecurityMetadataSource() {
58+
59+
return this.securityMetadataSource;
60+
}
61+
62+
63+
}

0 commit comments

Comments
 (0)