概要
Spring Security基于Spring框架,提供一套Web应用安全性的完整解决方案,侧重于为Java程序提供身份认证(Authentication)和授权(Authorization)。
用户认证:要求用户提供用户名和密码,系统校验用户名和密码完成认证过程。包括HTTP基本认证、HTTP表单验证、HTTP摘要认证、OpenID和LDAP等。
用户授权:指验证某个用户是否有权限执行某个操作。一般来说,系统会为不同用户分配不同的角色,每个角色对应不同的权限。Spring Security提供基于角色的访问控制,可以对应用中的领域对象进行细粒度的控制。
对于权限,细分为:
- 功能权限
- 访问权限
- 菜单权限
测试环境搭建
- 新建springboot项目web模块
- 导入静态资源,静态资源文件如下:(学习方便,这里直接导入了狂神的静态资源)
百度云自取:
链接:https://pan.baidu.com/s/1R-ojTYrFEYIc6inmxxIE1Q
提取码:cfta
3.写一个路由控制跳转测试:
package com.hyyan.bootspringsecurity.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @author: hyyan
* @date: 2021/7/4
* @description:
**/
@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;
}
}
- 测试环境搭建成功。
使用Spring Security
两个主要目标:“认证”和“授权”。
根据上面搭建的测试环境,所有人都可以访问。使用Spring Security加上认证和授权功能。
- 引入相关依赖:
<!--引入Spring Security模块-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
- 编写配置类:WebSecurityConfigurerAdapter 类是个适配器, 我们需要写个配置类去继承它,然后编写自己所需要的配置。(详细看注释)
package com.hyyan.bootspringsecurity.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;
/**
* @author: hyyan
* @date: 2021/7/4
* @description:
**/
@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().usernameParameter("username").passwordParameter("password").loginPage("/toLogin").loginProcessingUrl("/login");
http.csrf().disable();//关闭csrf功能:跨站请求伪造,默认只能通过post方式提交logout请求
//注销功能:注销成功跳到首页
http.logout().logoutSuccessUrl("/");
//记住我
http.rememberMe().rememberMeParameter("remember");
}
//认证
//密码编码:PasswordEncoder
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()) //从内存中读数据
.withUser("hyyan").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2")
.and()
.withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
.and()
.withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
}
}
-
authorizeRequests()配置路径拦截,表明路径访问所对应的权限,角色,认证信息。
-
formLogin()对应表单认证相关的配置 。
-
logout()对应注销相关的配置。
-
passwordEncoder():密码编码,将前端传过来的密码进行某种方式加密,否则就无法登录,报错:There is no PasswordEncoder mapped for the id “null”。
Spring Security 官方推荐的是使用bcrypt加密方式。 -
withUser():这里添加了三个拥有不同角色的用户。
-
inMemoryAuthentication()表示从内存读数据,但是一般情况我们是从数据库读数据的:
特殊需求实现
需求1:用户没有登录的时候,导航栏上只显示登录按钮,用户登录之后,导航栏可以显示登录的用户信息及注销按钮:
未登录:
已登录:
需求2:不同用户登录展示不同页面,根据上面代码设置,比如:
root用户拥有vip1、 vip2、vip3功能,那么登录则显示这三个功能;
guest用户拥有vip1功能,那么登录则显示这一个功能,而vip2、vip3的功能菜单不显示!
登录root用户:
登录guest用户:
实现
- 需要结合thymeleaf中的一些功能,引入依赖:
<!--引入thymeleaf依赖-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity5</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
- 修改前端页面,导入命名空间(index.html):
<html lang="en" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
- 导航栏增加认证判断:
sec:authorize=“isAuthenticated()”:是否认证登录,用来显示不同的页面
<!--如果未登录-->
<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">
<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>
- 角色功能模块认证:
sec:authorize="hasRole(‘vip1’)
sec:authorize="hasRole(‘vip2’)
sec:authorize="hasRole(‘vip3’)
<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 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" 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>
定制登录页
spring security有默认的登录页,如果要使用我们自己写的Login登录页,则需要在登录页配置后面指定 loginpage,以及配置接收登录的用户名和密码的参数,loginProcessingUrl()提交表单后跳转的地址:
http.formLogin().usernameParameter("username").passwordParameter("password").loginPage("/toLogin").loginProcessingUrl("/login");
前端也需要指向我们自己定义的 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>
<div class="field">
<input type="checkbox" name="remember">记住我
</div>
<input type="submit" class="ui blue submit button"/>
</form>
“记住我”的后端验证:
//记住我
http.rememberMe().rememberMeParameter("remember");
OK,完结!!