Spring Security
首先我们看下它的官网介绍:Spring Security官网地址https://spring.io/projects/spring-security#overview
也可以分等级测试 不同等级看到的东西不一样
实战测试
-
新建一个初始的springboot项目 web模块 , thymeleaf模块
-
导入静态资源
welcome.html
|views
|level1
1.html
2.html
3.html
|level2
1.html
2.html
3.html
|level3
1.html
2.html
3.html
Login.html
controller层
@Controller
public class RouterController {
@RequestMapping({"/","/index"})
public String index(){
return "index";
}
@RequestMapping("/toLogin")
public String toLogin(){
return "views/login";
}
@RequestMapping("/level1/{id}")
public String level1(@PathVariable("id") int id){
return "views/level1/"+id;
}
@RequestMapping("/level2/{id}")
public String level2(@PathVariable("id") int id){
return "views/level2/"+id;
}
@RequestMapping("/level3/{id}")
public String level3(@PathVariable("id") int id){
return "views/level3/"+id;
}
}
认证和授权
记住几个类:
-
WebSecurityConfifigurerAdapter: 自定义Security策略
-
AuthenticationManagerBuilder:自定义认证策略
-
@EnableWebSecurity:开启WebSecurity模式
Spring Security的两个主要目标是 “认证” 和 “授权”(访问控制)。
“认证”(Authentication)
身份验证是关于验证您的凭据,如用户名/用户ID和密码,以验证您的身份。
身份验证通常通过用户名和密码完成,有时与身份验证因素结合使用。
“授权” (Authorization)
授权发生在系统成功验证您的身份后,最终会授予您访问资源(如信息,文件,数据库,资金,位置,
几乎任何内容)的完全权限。
- 引入配置文件
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
- 编写基础配置类
@EnableWebSecurity // 开启WebSecurity模式
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override protected void configure(HttpSecurity http) throws Exception {
// 定制请求的授权规则
// 首页所有人可以访问
http.authorizeRequests().antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("vip1")
.antMatchers("/level2/**").hasRole("vip2")
.antMatchers("/level3/**").hasRole("vip3");
// 开启自动配置的登录功能
http.formLogin();
}
}
- 定义认证规则
//定义认证规则
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//在内存中定义,也可以在jdbc中去拿....
//Spring security 5.0中新增了多种加密方式,也改变了密码的格式。
//要想我们的项目还能够正常登陆,需要修改一下configure中的代码。我们要将前端传过来的密 码进行某种方式加密
//spring security 官方推荐的是使用bcrypt加密方式。
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("kuangshen").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
.and()
.withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
.and()
.withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2"); }
}
- 权限控制及注销
-
在condigure 添加http.logout();
-
在前端添加一个注销按钮
<a class="item" th:href="@{/logout}"> <i class="address card icon"></i> 注销 </a>
-
注销成功后返回首页
// .logoutSuccessUrl("/"); 注销成功来到首页
http.logout().logoutSuccessUrl("/");
实现不同等级显示不同的功能菜单
我们需要结合thymeleaf中的一些功能
sec:authorize=“isAuthenticated()”:是否认证登录! 来显示不同的页面
添加maven依赖
<!-- https://mvnrepository.com/artifact/org.thymeleaf.extras/thymeleaf- extras-springsecurity4 -->
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
导入命名空间
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5"
修改导航栏增加认证判断
<!--登录注销-->
<div class="right menu">
<!--如果未登录-->
<div sec:authorize="!isAuthenticated()">
<a class="item" th:href="@{/login}">
<i class="address card icon"></i> 登录
</a>
</div>
<!--如果已登录-->
<div sec:authorize="isAuthenticated()">
<a class="item">
<i class="address card icon"></i>
用户名: <span sec:authentication="principal.username">
</span>
角色:<span sec:authentication="principal.authorities">
</span>
</a>
</div>
<div sec:authorize="isAuthenticated()">
<a class="item" th:href="@{/logout}">
<i class="address card icon"></i> 注销
</a>
</div>
</div>
配置中增加
http.csrf().disable();//关闭csrf功能:跨站请求伪造,默认只能通过post方式提交logout 请求
http.logout().logoutSuccessUrl("/");
角色功能块认证
<!-- sec:authorize="hasRole('vip1')" -->
<div class="column" sec:authorize="hasRole('vip1')">
<div class="ui raised segment">
<div class="ui">
<div class="content">
<h5 class="content">Level 1</h5>
<hr>
<div><a th:href="@{/level1/1}"><i class="bullhorn icon">
</i> Level-1-1</a></div>
<div><a th:href="@{/level1/2}"><i class="bullhorn icon">
</i> Level-1-2</a></div>
<div><a th:href="@{/level1/3}"><i class="bullhorn icon">
</i> Level-1-3</a></div>
</div>
</div>
</div>
</div>
<div class="column" sec:authorize="hasRole('vip2')">
<div class="ui raised segment">
<div class="ui">
<div class="content">
<h5 class="content">Level 1</h5>
<hr>
<div><a th:href="@{/level1/1}"><i class="bullhorn icon">
</i> Level-1-1</a></div>
<div><a th:href="@{/level1/2}"><i class="bullhorn icon">
</i> Level-1-2</a></div>
<div><a th:href="@{/level1/3}"><i class="bullhorn icon">
</i> Level-1-3</a></div>
</div>
</div>
</div>
</div>
<div class="column" sec:authorize="hasRole('vip3')">
<div class="ui raised segment">
<div class="ui">
<div class="content">
<h5 class="content">Level 3</h5>
<hr>
<div><a th:href="@{/level3/1}"><i class="bullhorn icon">
</i> Level-3-1</a></div>
<div><a th:href="@{/level3/2}"><i class="bullhorn icon">
</i> Level-3-2</a></div>
<div><a th:href="@{/level3/3}"><i class="bullhorn icon">
</i> Level-3-3</a></div>
</div>
</div>
</div>
</div>
记住我
http.rememberMe(); 安全配置加这一句
定制登陆页
- 在登录页配置后指定loginpage
http.formLogin().loginPage("/toLogin");
- 前端定义login请求
<a class="item" th:href="@{/toLogin}">
<i class="address card icon"></i> 登录
</a>
发送信息的位置
<form th:action="@{/login}" method="post">
<div class="field">
<label>Username</label>
<div class="ui left icon input">
<input type="text" placeholder="Username" name="username">
<i class="user icon"></i>
</div>
</div>
<div class="field">
<label>Password</label>
<div class="ui left icon input">
<input type="password" name="password">
<i class="lock icon"></i>
</div>
</div>
<input type="submit" class="ui blue submit button"/>
</form>
- 配置登陆的用户名密码和参数
http.formLogin()
.usernameParameter("username")
.passwordParameter("password")
.loginPage("/toLogin")
.loginProcessingUrl("/login"); // 登陆表单提交请求 12345
- 在登陆页增加记住我
<input type="checkbox" name="remember"> 记住我
- 后端验证处理
//定制记住我的参数!
http.rememberMe().rememberMeParameter("remember");
完整代码:https://gitee.com/fanshuaishuai/security