前言
市面上常见的两种安全框架:
- shiro是一个强大易用的安全框架,用户群体非常多
- spring security比较复杂,功能强大,能够无缝地整合spring
Spring Security是针对Spring项目的安全框架,也是Spring Boot底层安全模 块默认的技术选型。他可以实现强大的web安全控制。对于安全控制,我们仅 需引入spring-boot-starter-security模块,进行少量的配置,即可实现强大的 安全管理,例如身份认证,权限控制,防止漏洞攻击等等。
认证和授权
应用程序的两个主要区域是“认证”和“授权”(或者访问控制)。 这两个主要区域是Spring Security 的两个目标。
这两个概念是通用的而不只在Spring Security中。
认证
“认证”(Authentication),是建立一个他声明的主体的过程(一个“主体”一般是指用户,设备或一些可以在你的应用程序中执行动 作的其他系统)。
授权
“授权”(Authorization)指确定一个主体是否允许在你的应用 执行一个动作的过程。为了抵达需要授权的店,主体的身份已经有认 证过程建立。
演示
官网guide
完整示例地址
引入SpringSecurity
1
2
3
4
|
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
|
添加后端逻辑
步骤:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
package com.eh.security;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* 1、引入SpringSecurity;
* 2、编写SpringSecurity的配置类;
* @EnableWebSecurity extends WebSecurityConfigurerAdapter
* 3、控制请求的访问权限:
* configure(HttpSecurity http) {
* http.authorizeRequests().antMatchers("/").permitAll()
* .antMatchers("/level1/**").hasRole("VIP1")
* }
* 4、定义认证规则:
* configure(AuthenticationManagerBuilder auth){
* auth.inMemoryAuthentication()
* .withUser("zhangsan").password("123456").roles("VIP1","VIP2")
* }
* 5、开启自动配置的登陆功能:
* configure(HttpSecurity http){
* http.formLogin();
* }
* 6、注销:http.logout();
* 7、记住我:Remeberme();
*/
@SpringBootApplication
public class SecurityApplication {
public static void main(String[] args) {
SpringApplication.run(SecurityApplication.class, args);
}
}
|
配置
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
package com.eh.security.config;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@EnableWebSecurity
public class MySecurityConfig extends WebSecurityConfigurerAdapter {
// 定制授权规则
@Override
protected void configure(HttpSecurity http) throws Exception {
//super.configure(http);
//定制请求的授权规则
http.authorizeRequests().antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("VIP1")
.antMatchers("/level2/**").hasRole("VIP2")
.antMatchers("/level3/**").hasRole("VIP3");
//开启自动配置的登陆功能,效果,如果没有登陆,没有权限就会来到登陆页面
http.formLogin().usernameParameter("user").passwordParameter("pwd")
.loginPage("/userlogin");
//1、/login来到登陆页
//2、重定向到/login?error表示登陆失败
//3、更多详细规定
//4、默认post形式的 /login代表处理登陆
//5、一但定制loginPage;那么 loginPage的post请求就是登陆
//开启自动配置的注销功能。
http.logout().logoutSuccessUrl("/");//注销成功以后来到首页
//1、访问 /logout 表示用户注销,清空session
//2、注销成功会返回 /login?logout 页面;
//开启记住我功能
http.rememberMe().rememberMeParameter("remeber");
//登陆成功以后,将cookie发给浏览器保存,以后访问页面带上这个cookie,只要通过检查就可以免登录
//点击注销会删除cookie
}
//定义认证规则
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//super.configure(auth);
// 默认定义用户存在内存中,实际开发存在数据库中auth.jdbcAuthentication()
/**
* 和其他加密方式相比,BCryptPasswordEncoder有着它自己的优势所在,首先加密的hash值每次都不同,就像md5的盐值加密一样,
* 只不过盐值加密用到了随机数,前者用到的是其内置的算法规则,毕竟随机数没有设合适的话还是有一定几率被攻破的。
* 其次BCryptPasswordEncoder的生成加密存储串也有60位之多。最重要的一点是,md5的加密不是spring security所推崇的加密方式了,
* 所以我们还是要多了解点新的加密方式。
*
* 通过传入的值进行BCryptPasswordEncoder加密,然后获取,再保存。
*
* 由于每次的hash值都不同,导致加密密文都不一样,其实这才是我们所希望看到的,而不是千篇一律。
*
* 通过加密密文后,密码可以加密了,但是我们会发现输入123456的密码进行登录时登录不了的,为什么?
* 因为它识别不了我们加密密文和明文之间的转换,你需要告诉spring,我已经将明文进行转换,
* 这里使用new BCryptPasswordEncoder().encode("密码")来解决
*/
auth.inMemoryAuthentication()
.passwordEncoder(new BCryptPasswordEncoder())
.withUser("zhangsan").password(new BCryptPasswordEncoder().encode("123")).roles("VIP1", "VIP2")
.and()
.withUser("lisi").password(new BCryptPasswordEncoder().encode("123")).roles("VIP2", "VIP3")
.and()
.withUser("wangwu").password(new BCryptPasswordEncoder().encode("123")).roles("VIP1", "VIP3");
}
}
|
添加前端逻辑
为了在thymeleaf中使用类似<div sec:authorize="hasRole('VIP1')">
语法还需要引入
1
2
3
4
|
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
</dependency>
|
同时在html页面引入namespace
1
2
|
<html xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
|
welcome.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1 align="center">欢迎光临武林秘籍管理系统</h1>
<div sec:authorize="!isAuthenticated()">
<h2 align="center">游客您好,如果想查看武林秘籍 <a th:href="@{/userlogin}">请登录</a></h2>
</div>
<div sec:authorize="isAuthenticated()">
<h2><span sec:authentication="name"></span>,您好,您的角色有:
<span sec:authentication="principal.authorities"></span></h2>
<form th:action="@{/logout}" method="post">
<input type="submit" value="注销"/>
</form>
</div>
<hr>
<div sec:authorize="hasRole('VIP1')">
<h3>普通武功秘籍</h3>
<ul>
<li><a th:href="@{/level1/1}">罗汉拳</a></li>
<li><a th:href="@{/level1/2}">武当长拳</a></li>
<li><a th:href="@{/level1/3}">全真剑法</a></li>
</ul>
</div>
<div sec:authorize="hasRole('VIP2')">
<h3>高级武功秘籍</h3>
<ul>
<li><a th:href="@{/level2/1}">太极拳</a></li>
<li><a th:href="@{/level2/2}">七伤拳</a></li>
<li><a th:href="@{/level2/3}">梯云纵</a></li>
</ul>
</div>
<div sec:authorize="hasRole('VIP3')">
<h3>绝世武功秘籍</h3>
<ul>
<li><a th:href="@{/level3/1}">葵花宝典</a></li>
<li><a th:href="@{/level3/2}">龟派气功</a></li>
<li><a th:href="@{/level3/3}">独孤九剑</a></li>
</ul>
</div>
</body>
</html>
|