Skip to content

Commit 4f7ab35

Browse files
authored
Merge pull request #1 from Snailclimb/master
update
2 parents b1e6b2c + 271916b commit 4f7ab35

File tree

70 files changed

+2211
-524
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

70 files changed

+2211
-524
lines changed

README-ENGLISH.md

+9
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,19 @@
11
# spring-security-jwt-guide
22

3+
## Introduce
4+
5+
[Spring Security](https://spring.io/projects/spring-security ) is a very powerful framework in the Spring family for authentication and permission control, and we can easily extend it to meet our current system security requirements.
6+
7+
However, compared with some other technologies such as JPA, Spring Security is more difficult to get started. Many people can hardly write a Demo independently after reading video or sending documents, so they may give up learning this thing later.
8+
9+
Spring Security, a powerful Security authentication framework, has been used in the induction training practical project when I first came to the company and the projects I am working on now. It can be seen that this framework is a good choice in the field of authentication and permission authentication. I am not familiar with Spring Security because I did not make this part of the module of the previous project by myself. So I took the time to learn this part of knowledge and implemented a simple Demo. This Demo mainly USES **Spring Security** and **Spring Boot**, and all the dependencies adopt the latest stable version. Beyond the initial project, the JPA technology was also used. The code structure of the project is as follows (chrome plug-in: octree), which is relatively clear as a whole. Due to my limited ability and time, there must be a lot of areas that can be optimized. Interested friends can improve it together.
10+
311
## Setup
412

513
1. git clone https://github.com/Snailclimb/spring-security-jwt-guide.git
614
2. open project and wait maven to install project Dependencies
715
3. change `application.properties` change the database connection information parameter to your own
16+
4. Run the project (related data tables will be created automatically, if you don't understand, take a look at JPA)
817

918
## Example
1019

README.md

+98-13
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,120 @@
1-
# spring-security-jwt-guide
21

3-
[English version](https://github.com/Snailclimb/spring-security-jwt-guide/blob/master/README-ENGLISH.md)
2+
# spring-security-jwt-guide
43

54
**如果国内访问缓慢的话,可以通过码云查看:** https://gitee.com/SnailClimb/spring-security-jwt-guide
65

7-
## 下载配置
6+
## 前言
7+
8+
[Spring Security](https://spring.io/projects/spring-security ) 是 Spring 全家桶中非常强大的一个用来做身份验证以及权限控制的框架,我们可以轻松地扩展它来满足我们当前系统安全性这方面的需求。
9+
10+
但是 Spring Security 相比于其他一些技术比如 JPA 来说更难上手,很多人初学的时候很难通过看视频或者文档发就很快能独立写一个 Demo 出来,于是后面可能就放弃了学习这个东西。
11+
12+
刚来公司的时候的入职培训实战项目以及现在正在做的项目都用到了 Spring Security 这个强大的安全验证框架,可以看出这个框架在身份验证以及权限验证领域可以说应该是比较不错的选择。由于之前经历项目的这部分模块都不是自己做的,所以对于 Spring Security 并不是太熟悉。于是自/己抽时间对这部分知识学习了一下,并实现了一个简单的 Demo 。这个 Demo 主要用到了 **Spring Security****Spring Boot** 这两门技术,并且所有的依赖采用的都是最新的稳定版本。初次之外,这个项目还用到了 JPA 这门技术。
13+
14+
由于自己的能力以及时间有限,所以一定还有很多可以优化的地方,有兴趣的朋友可以一起完善,期待你的 PR。
15+
16+
## 介绍
17+
18+
**项目用到的一些框架/服务:**
19+
20+
- **数据库**: H2内存数据库,无需手动安装。
21+
- **缓存**: Redis
22+
- **权限框架** :Spring Security
23+
- **ORM框架** :JPA (低SQL)
24+
- **接口文档** : swagger。在线 API 文档地址:[http://localhost:9333/api/swagger-ui/](http://localhost:9333/api/swagger-ui/)
25+
26+
**你能从这个项目中学习到什么?**
27+
28+
1. Spring Security +JWT 实现登入登出以及权限校验
29+
2. JPA 实现审计功能、多对多的映射关系如何通过关联表实现
30+
31+
## 教程
32+
33+
1. [项目讲解/分析](./docs/SpringSecurity介绍.md) (内容待重构)
34+
2. [swagger3.0整合](./docs/swagger.md)
35+
36+
## 代办
37+
38+
- [x] 增加H2内存数据库支持,无须MySQL,一键启动项目启动后访问 `http://{host}:9333/h2-console/` (数据库 url 地址、用户名和密码都在 `application.properties` 配置文件中)
39+
- [x] 增加Swagger,方便调用接口
40+
- [x] 异常处理部分代码重构,优化返回结构
41+
- [x] 新建一个role表,然后通过新建一个role_user表的形式,将用户与角色关联起来
42+
- [x] 文件结构重构
43+
- [x] 增加jpa审计功能
44+
- [x] login(登录)接口在controller层暴露出来
45+
- [x] 登出功能:redis保存token信息(key->user id,value->token),登出后将 redis中的token信息删除
46+
- [x] 重新登录将上一次登录生成的token弄失效(解决未过期的token还是可以用的问题):重新登录会将 redis 中保存的 token 信息进行更新
47+
- [ ] 重构详解文章
48+
49+
## 项目概览
50+
51+
为了区分,我把 Spring Security相关的都单独放在了一个文件夹下面。
52+
53+
![](./pictures/structure.png)
54+
55+
56+
## 如何运行项目
857

958
1. git clone https://github.com/Snailclimb/spring-security-jwt-guide.git
10-
2. 打开项目并且等待Maven下载好相关依赖。建议使用idea 打开,并确保你的idea 下载了 lombok插件。
11-
3. 修改 `application.properties` 将数据库连接信息改成你自己的。
59+
2. 打开项目并且等待 Maven 下载好相关依赖。建议使用 Intellij IDEA 打开,并确保你的 Intellij IDEA 下载了 lombok 插件。
60+
3. 下载 redis 并`application.yaml`中redis的配置
61+
4. 运行项目(相关数据表会被自动创建,不了解的看一下 JPA)
62+
1263
## 示例
1364

1465
### 1.注册一个账号
1566

16-
![Register](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-7/1-register.png)
67+
**URL:**
68+
69+
`POST http://localhost:9333/api/users/sign-up`
70+
71+
**RequestBody:**
72+
73+
```json
74+
{"userName":"123456","fullName":"shuangkou","password":"123456"}
75+
```
76+
77+
![注册](./pictures/sign-up.png)
78+
79+
新注册的用户默认绑定的角色为:用户(USER)和管理者(MANAGER)。
1780

1881
### 2.登录
1982

20-
![Login](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-7/2-login.png)
83+
**URL:**
84+
85+
`POST http://localhost:9333/api/auth/login`
86+
87+
**RequestBody:**
88+
89+
```json
90+
{"username": "123456", "password": "123456","rememberMe":true}
91+
```
92+
93+
![登录](./pictures/login.png)
94+
95+
96+
### 3.使用正确 Token 访问需要进行身份验证的资源
97+
98+
我们使用 GET 请求访问 `/api/users`,这个接口的访问权限是
99+
100+
```java
101+
@PreAuthorize("hasAnyRole('ROLE_USER','ROLE_MANAGER','ROLE_ADMIN')")
102+
```
103+
104+
![Access resources that require authentication](./pictures/access-resources-that-require-authentication.png)
105+
106+
### 4.不带 Token 或者使用无效 Token 访问
21107

22-
### 3.使用正确Token访问需要进行身份验证的资源
108+
我们使用 GET 请求访问 `/api/users`,但是不带token或者带上无效token。
23109

24-
![Access resources that require authentication](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-7/3-visit-authenticated-resourse-have-token.png)
25110

26-
### 4.不带Token访问需要进行身份验证的资源
111+
![Access resources that require authentication without token or with invalid token](./pictures/access-resources-that-require-authentication2.png)
27112

28-
![Access resources that require authentication without token](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-7/4-visit-authenticated-resourse-not-have-token.png)
113+
### 5.带了正确Token但是访问权限
29114

30-
### 5.使用不正确Token访问需要进行身份验证的资源
115+
我们使用 DELETE 请求访问 `/api/users?username=xxx`,携带有效的 token ,但是 token 的访问权限不够。
31116

32-
![Access resources that require authentication with not correct token](https://my-blog-to-use.oss-cn-beijing.aliyuncs.com/2019-7/5-visit-authenticated-resourse-not-have-valid-token.png)
117+
![](./pictures/not-have-enough-permission.png)
33118

34119
## 参考
35120

config/checkstyle/checkstyle.xml

+178
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,178 @@
1+
<?xml version="1.0"?>
2+
<!DOCTYPE module PUBLIC
3+
"-//Puppy Crawl//DTD Check Configuration 1.3//EN"
4+
"http://checkstyle.sourceforge.net/dtds/configuration_1_3.dtd">
5+
6+
<!--
7+
8+
Checkstyle configuration that checks the sun coding conventions from:
9+
10+
- the Java Language Specification at
11+
http://java.sun.com/docs/books/jls/second_edition/html/index.html
12+
13+
- the Sun Code Conventions at http://java.sun.com/docs/codeconv/
14+
15+
- the Javadoc guidelines at
16+
http://java.sun.com/j2se/javadoc/writingdoccomments/index.html
17+
18+
- the JDK Api documentation http://java.sun.com/j2se/docs/api/index.html
19+
20+
- some best practices
21+
22+
Checkstyle is very configurable. Be sure to read the documentation at
23+
http://checkstyle.sf.net (or in your downloaded distribution).
24+
25+
Most Checks are configurable, be sure to consult the documentation.
26+
27+
To completely disable a check, just comment it out or delete it from the file.
28+
29+
Finally, it is worth reading the documentation.
30+
31+
-->
32+
33+
<module name="Checker">
34+
<!--
35+
If you set the basedir property below, then all reported file
36+
names will be relative to the specified directory. See
37+
http://checkstyle.sourceforge.net/5.x/config.html#Checker
38+
39+
<property name="basedir" value="${basedir}"/>
40+
-->
41+
42+
<property name="fileExtensions" value="java, properties, xml"/>
43+
44+
<!-- Checks that a resource-info.java file exists for each resource. -->
45+
<!-- See http://checkstyle.sf.net/config_javadoc.html#JavadocPackage -->
46+
<!--<module name="JavadocPackage"/>-->
47+
48+
<!-- Checks whether files end with a new line. -->
49+
<!-- See http://checkstyle.sf.net/config_misc.html#NewlineAtEndOfFile -->
50+
51+
<!-- Checks that property files contain the same keys. -->
52+
<!-- See http://checkstyle.sf.net/config_misc.html#Translation -->
53+
<module name="NewlineAtEndOfFile">
54+
<property name="severity" value="ignore" />
55+
</module>
56+
<module name="Translation"/>
57+
58+
<!-- Checks for Size Violations. -->
59+
<!-- See http://checkstyle.sf.net/config_sizes.html -->
60+
<module name="FileLength"/>
61+
62+
<!-- Checks for whitespace -->
63+
<!-- See http://checkstyle.sf.net/config_whitespace.html -->
64+
<module name="FileTabCharacter"/>
65+
66+
<!-- Miscellaneous other checks. -->
67+
<!-- See http://checkstyle.sf.net/config_misc.html -->
68+
<module name="RegexpSingleline">
69+
<property name="format" value="\s+$"/>
70+
<property name="minimum" value="0"/>
71+
<property name="maximum" value="0"/>
72+
<property name="message" value="Line has trailing spaces."/>
73+
</module>
74+
75+
<!-- Checks for Headers -->
76+
<!-- See http://checkstyle.sf.net/config_header.html -->
77+
<!-- <module name="Header"> -->
78+
<!-- <property name="headerFile" value="${checkstyle.header.file}"/> -->
79+
<!-- <property name="fileExtensions" value="java"/> -->
80+
<!-- </module> -->
81+
82+
<module name="SuppressWarningsFilter"/>
83+
<module name="TreeWalker">
84+
<module name="SuppressWarningsHolder"/>
85+
86+
<!-- Checks for Javadoc comments. -->
87+
<!-- See http://checkstyle.sf.net/config_javadoc.html -->
88+
<!--
89+
<module name="JavadocMethod"/>
90+
<module name="JavadocType"/>
91+
<module name="JavadocVariable"/>
92+
<module name="JavadocStyle"/>
93+
-->
94+
95+
<!-- Checks for Naming Conventions. -->
96+
<!-- See http://checkstyle.sf.net/config_naming.html -->
97+
<module name="ConstantName"/>
98+
<module name="LocalFinalVariableName"/>
99+
<module name="LocalVariableName"/>
100+
<module name="MemberName"/>
101+
<module name="MethodName"/>
102+
<module name="PackageName"/>
103+
<module name="ParameterName"/>
104+
<module name="StaticVariableName"/>
105+
<module name="TypeName"/>
106+
107+
<!-- Checks for imports -->
108+
<!-- See http://checkstyle.sf.net/config_import.html -->
109+
<!--<module name="AvoidStarImport"/>-->
110+
<module name="RedundantImport">
111+
<!-- Checks for redundant import statements. -->
112+
<property name="severity" value="error"/>
113+
</module>
114+
115+
<!-- Checks for Size Violations. -->
116+
<!-- See http://checkstyle.sf.net/config_sizes.html -->
117+
<module name="MethodLength"/>
118+
<module name="ParameterNumber">
119+
<property name="max" value="16"/>
120+
<property name="ignoreOverriddenMethods" value="true"/>
121+
</module>
122+
<module name="UnusedImports">
123+
<property name="processJavadoc" value="true"/>
124+
</module>
125+
<!-- Checks for whitespace -->
126+
<!-- See http://checkstyle.sf.net/config_whitespace.html -->
127+
<module name="EmptyForIteratorPad"/>
128+
<module name="GenericWhitespace"/>
129+
<module name="MethodParamPad"/>
130+
<module name="NoWhitespaceAfter"/>
131+
<module name="NoWhitespaceBefore"/>
132+
<module name="ParenPad"/>
133+
<module name="TypecastParenPad"/>
134+
<module name="WhitespaceAfter"/>
135+
<module name="WhitespaceAround"/>
136+
137+
<!-- Modifier Checks -->
138+
<!-- See http://checkstyle.sf.net/config_modifiers.html -->
139+
<module name="ModifierOrder"/>
140+
<module name="RedundantModifier"/>
141+
142+
<!-- Checks for blocks. You know, those {}'s -->
143+
<!-- See http://checkstyle.sf.net/config_blocks.html -->
144+
<module name="AvoidNestedBlocks"/>
145+
<module name="EmptyBlock"/>
146+
<module name="LeftCurly"/>
147+
<module name="NeedBraces"/>
148+
<module name="RightCurly"/>
149+
150+
<!-- Checks for common coding problems -->
151+
<!-- See http://checkstyle.sf.net/config_coding.html -->
152+
<!--<module name="AvoidInlineConditionals"/>-->
153+
<module name="EmptyStatement"/>
154+
<module name="EqualsHashCode"/>
155+
<!--<module name="HiddenField"/>-->
156+
<module name="IllegalInstantiation"/>
157+
<module name="InnerAssignment"/>
158+
<!--<module name="MagicNumber"/>-->
159+
<module name="MissingSwitchDefault"/>
160+
<module name="SimplifyBooleanExpression"/>
161+
<module name="SimplifyBooleanReturn"/>
162+
163+
<!-- Checks for class design -->
164+
<!-- See http://checkstyle.sf.net/config_design.html -->
165+
<!--<module name="DesignForExtension"/>-->
166+
<module name="FinalClass"/>
167+
<module name="InterfaceIsType"/>
168+
<module name="VisibilityModifier"/>
169+
170+
<!-- Miscellaneous other checks. -->
171+
<!-- See http://checkstyle.sf.net/config_misc.html -->
172+
<module name="ArrayTypeStyle"/>
173+
<module name="TodoComment"/>
174+
<module name="UpperEll"/>
175+
176+
</module>
177+
178+
</module>

docs/H2内存数据库介绍.md

+11
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
### 1.什么是H2数据库?
2+
3+
H2是用Java编写的内存数据库。
4+
5+
### 2.为什么要用H2数据库?什么时候用?
6+
7+
因为是内存数据库,所以h2的速度比一般的关系型数据库快很多,一般用于单元测试环境。
8+
9+
10+
11+
![](../pictures/h2-collection.png)

0 commit comments

Comments
 (0)