SpringSecurity
1、什么是SpringSecurity?
官方解读: Spring Security是一个强大的和高度可定制的身份验证和访问控制框架。 它是保证基于spring的应用程序安全的实际标准。
- 认证 (你是谁)
- 授权 (你能干什么)
- 攻击防护 (防止伪造身份)
准备工作:
创建一个springboot项目,添加springweb依赖,添加thymeleaf依赖以及security依赖
<!--thymeleaf-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.5.5</version>
</dependency>
<!-- 覆盖thymeleaf版本依赖 -->
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
<!--security-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
导入静态资源:
关闭thymeleaf页面缓存:
spring.thymeleaf.cache=false
创建controller层,编写视图跳转的controller
@Controller
public class RouterController {
@RequestMapping("/index")
public String MainPage(){
return "/index";
}
@RequestMapping("/toLogin")
public String Login(){
return "/views/login";
}
@RequestMapping("/level1/{id}")
public String Level1(@PathVariable("id") Integer id){
return "/views/level1/"+id;
}
@RequestMapping("/level2/{id}")
public String Level2(@PathVariable("id")Integer id){
return "/views/level1/"+id;
}
@RequestMapping("/level3/{id}")
public String Level3(@PathVariable("id")Integer id){
return "/views/level1/"+id;
}
}
2、认证跟授权
记得添加security的依赖包
<!--security-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
新建一个配置类:继承webSecurityConfigurerAdapter,添加@EnableWebSecurity注解
- 授权:重写configure(HttpSecurity http)方法
- 没有权限默认跳转至登录页:http.formLogin();
- 认证:重写configure(AuthenticationManagerBuilder auth)方法
- 对密码进行加密:new BCryptPasswordEncoder()
@EnableWebSecurity
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();
}
//认证
//密码编码:PasswordEncoder
//在Spring Security 5.0+新增了许多加密方法
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("lengzher").password(new BCryptPasswordEncoder().encode("123123")).roles("vip1","vip2")
.and()
.withUser("root").password(new BCryptPasswordEncoder().encode("123123")).roles("vip1","vip2","vip3")
.and()
.withUser("guest").password(new BCryptPasswordEncoder().encode("123123")).roles("vip1");
}
}
3、注销和权限控制
注销功能:
在configure(HttpSecurity http)方法中使用
//注销
http.logout().logoutSuccessUrl("/");//开启注销功能,注销后返回首页
在pom.xml中导入thymeleaf和security的整合包(springboot版本2.5+的导security5,以下版本到security4)
<!--thymeleaf-security整合包-->
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
前端导入命名空间
xmlns:sec="http://www.thymeleaf.org/extras/spring-security"
设置登录以及未登录时显示的内容
<!--登录注销-->
<div class="right menu">
<!--如果没有登录-->
<div sec:authorize="!isAuthenticated()">
<a class="item" th:href="@{/toLogin}">
<i class="address card icon"></i> 登录
</a>
</div>
<div sec:authorize="isAuthenticated()">
<!--如果登录:用户名,角色-->
<!--角色和用户名-->
<a class="item">
用户名:<span sec:authentication="name"></span>
角色:<span sec:authentication="principal.authorities"></span>
</a>
</div>
<div sec:authorize="isAuthenticated()">
<!--如果登录:注销-->
<!--注销-->
<a class="item" th:href="@{/logout}">
<i class="sign-out icon"></i> 注销
</a>
</div>
</div>
权限控制:
拥有vip角色的用户可以看到vip的内容
<div class="column" sec:authorize="hasRole('vip1')"></div>
<div class="ui raised segment" sec:authorize="hasRole('vip2')"></div>
<div class="ui raised segment" sec:authorize="hasRole('vip3')"></div>
<div>
<br>
<div class="ui three column stackable grid">
<!--动态菜单的效果-->
<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">
<div class="ui raised segment" sec:authorize="hasRole('vip2')">
<div class="ui">
<div class="content">
<h5 class="content">Level 2</h5>
<hr>
<div><a th:href="@{/level2/1}"><i class="bullhorn icon"></i> Level-2-1</a></div>
<div><a th:href="@{/level2/2}"><i class="bullhorn icon"></i> Level-2-2</a></div>
<div><a th:href="@{/level2/3}"><i class="bullhorn icon"></i> Level-2-3</a></div>
</div>
</div>
</div>
</div>
<div class="column">
<div class="ui raised segment" sec:authorize="hasRole('vip3')">
<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>
</div>
</div>
4、登录页面定制
在configure(HttpSecurity http)方法中开启登录页面:
//没有权限默认会到登录页面,需要开启登录页面
http.formLogin().loginPage("/toLogin").usernameParameter("username").passwordParameter("password").loginProcessingUrl("/login");
记住我配置
//记住我,存储在cookie,默认时间14天
http.rememberMe().rememberMeParameter("remember");
前端编写表单
<!--如果要使用toLogin,则http.formLogin().loginPage("/toLogin");配置一致。
如果非要使用login,则http.formLogin().loginPage("/toLogin").loginProcessingUrl("/login");
-->
<form th:action="@{/login}" method="post">
<div class="field">
<label>工号</label>
<div class="ui left icon input">
<input type="text" placeholder="请输入工号..." name="username">
<i class="user icon"></i>
</div>
</div>
<div class="field">
<label>密码</label>
<div class="ui left icon input">
<input type="password" placeholder="请输入密码..." name="password">
<i class="lock icon"></i>
</div>
</div>
<div class="field">
<input type="checkbox" name="remember">记住我
</div>
<input type="submit" class="ui blue submit button"/>
</form>