SpringBoot学习系列(十七)------SpringBoot与Spring Security
前言
权限校验和授权认证是我们日常项目中不可获取的两个功能模块,在目前市面上,有apache旗下的shiro和Spring团队的Spring Security两款安全框架是比较流行了,既然我们使用的是SrpingBoot,那就来看一下如何使用SpringSecurity吧!
正文
1. 创建一个SpringBoot工程
我们先创建一个简单的SpringBoot项目,引入Thymeleaf的依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.xiaojian</groupId>
<artifactId>springboot-security</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>springboot-security</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
然后我们有一个TeGongCOntroller
:
package com.xiaojian.security.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
@Controller
public class TeGongController {
private final String PREFIX = "pages/";
/**
* 欢迎页
* @return
*/
@GetMapping("/")
public String index() {
return "welcome";
}
/**
* 登陆页
* @return
*/
@GetMapping("/userlogin")
public String loginPage() {
return PREFIX+"login";
}
/**
* level1页面映射
* @param path
* @return
*/
@GetMapping("/level1/{path}")
public String level1(@PathVariable("path")String path) {
return PREFIX+"level1/"+path;
}
/**
* level2页面映射
* @param path
* @return
*/
@GetMapping("/level2/{path}")
public String level2(@PathVariable("path")String path) {
return PREFIX+"level2/"+path;
}
/**
* level3页面映射
* @param path
* @return
*/
@GetMapping("/level3/{path}")
public String level3(@PathVariable("path")String path) {
return PREFIX+"level3/"+path;
}
}
现在没有加入安全校验,我们来看一下项目启动的情况:
这个简单的页面中,有三种特工的档案分类,由于我们目前没有加入权限模块,所以任何用户都可以来访问每一个特工的信息:
2. 引入Security模块依赖
为了实现页面的认证和授权,我们在pom文件中加入Security
的依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
加入依赖以后我们重启项目,可以发现,直接跳转来到一个页面;
这是SpringSecurity整合SpringBoot以后帮我们自动配置的一个页面,我们可以在对应的自动配置类中找到相关的代码
现在,我们要自己定义请求的授权规则,就要进行如下处理:
- 自定义一个类继承
WebSecurityConfigurerAdapter
- 在该类上添加注解
@EnableWebSecurity
- 重写该类的configure方法来完成自定义的认证和授权
按照以上的步骤,我们创建这个类,并定义了自己的认证和授权信息:
/**
* 权限校验配置类
*/
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
/**
* 自定义授权规则
* @param http
* @throws Exception
*/
@Override
protected void configure(HttpSecurity http) throws Exception {
//antMatchers方法指定一个请求路径,hasRole方法给该请求资源增加一个角色
//只有访问的用户有该角色才能访问
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("UP1")
.antMatchers("/level2/**").hasRole("UP2")
.antMatchers("/level3/**").hasRole("UP3");
//开启自动配置的登录功能,如果访问的用户没有登录,会来到Security提供的登录页
//可以用usernameParameter和passwordParameter两个方法来指定登录页面from表单的参数名
http.formLogin().usernameParameter("user").passwordParameter("pwd")
//loginPage方法指定我们自己的登录页面,如果指定了自己的登录页面,那么
//页面from表单的提交地址及时该页面访问地址的POST方式
//比如下面这个登录页面,我们访问/userlogin的时候,请求会由controller映射到我们自己
//的登录页面,那么页面的from表单的提交地址就是post方式的/userlogin
.loginPage("/userlogin");
//我们还可以开启security提供的自动注销的功能
//logoutSuccessUrl表示,如果注销成功后的请求地址
http.logout().logoutSuccessUrl("/");
//开启记住我功能
//rememberMeParameter指定记住我单选款的属性名
//登录成功后,security会将用户信息发给浏览器保存在cookie中,注销后就删除该cookie
http.rememberMe().rememberMeParameter("remeber");
}
/**
* 定义认证规则
* @param auth
* @throws Exception
*/
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//我们可以自定义一个账号,并赋予权限
//withUser方法定义用户名,pssword定义密码,roles方法为当前账号赋予角色
//需要注意的是,Security5.0以后,对用户的登录密码新增了很多的机密方式,如果我们
//不指定加密方式,直接用psssword方法指定密码会报错,因此要设置加密方式,且对密码加密
//spring官方推荐使用的加密方式是bcrypt,我们这里就使用这种
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("admin")
.password(new BCryptPasswordEncoder().encode("123456"))
.roles("UP1", "UP2")
.and()
.withUser("root")
.password(new BCryptPasswordEncoder().encode("123456"))
.roles("UP2", "UP3");
}
}
关于SpringSecurity的一些基本使用都在上面的代码中,其实除了这些简单的使用,SpringSecurity还提供了预防跨站请求伪造CSRF功能,这个就不在这里赘述了,需要了解的可以直接去百度即可.
总结
SpringSecurity为我们提供了方便的权限控制和认证管理,我们可以很快速的完成项目的权限配置,当然,更加复杂的安全防护还需要更进一步的了解,这里只浅尝辄止.