简介:
Spring Security是针对Spring项目的安全框架,也是Spring Boot底层安全模块默认的技术选型,他可以实现强大的Web安全控制,对于安全控制,我们仅需要引入spring-boot-starter-security模块,进行少量的配置,即可实现强大的安全管理!
记住几个类:
webSecurityConfigurerAdapter:自定义Security策略.
AuthenticationManagerBuilder:自定义认证策略
EnableWebSecurity:开启WebSecurity模式
Spring Security的两个主要目标是“认证"和“授权”(访问控制)。
“认证”(Authentication)
“授权”(Authorization)
这个概念是通用的,而不是只在Spring Security中存在。
一、Security搭建环境?
1、首先新建一个springboot项目,只够选web中的spring web依赖

2、然后在pom.xml导入相关依赖
<!--thymeleaf-springsecurity4-->
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
<!--thymeleaf模块-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
3、导入静态资源资源
链接:https://pan.baidu.com/s/1xcM6UfI7hcywzjmOHw52Cw
提取码:wnlz
在application.properties配置文件里关掉thymeleaf模板缓存,以方便进行我们的测试
#关掉thymeleaf模板缓存,以方便进行我们的测试
spring.thymeleaf.cache=false
4、紧接着新建一个controller包,在包下编写一个controller类RouterController,作为我们的路由转发

代码如下:
package com.jowell.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class RouterController {
@RequestMapping({"/", "/index"})
public String index() {
return "index";
}
@RequestMapping("/login")
public String login() {
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;
}
}
配置完成启动测试

二、用户认证和授权
创建一个config包,编写一个SecurityConfig类
完整代码如下:
package com.jowell.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 SecurityConfig extends WebSecurityConfigurerAdapter {
//链式编程
// 授权
@Override
protected void configure(HttpSecurity http) throws Exception {
// 首页所有人可以访问,功能页只有对应权限的人才能访问
// 请求授权的规则
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("level1")
.antMatchers("/level2/**").hasRole("level2")
.antMatchers("/level3/**").hasRole("level3");
// 没有权限默认会跳到登录页面,需要开启登录的页面
http.formLogin();
// 防止网站攻击:get;post
http.csrf().disable();//关闭csrf(跨站请求伪造)功能,登出失败可能产生的原因
// 开启注销功能
http.logout().logoutSuccessUrl("/");
}
// 认证,springboot 2.1.x可以直接使用,其他版本会报错(或者采用下面的密码编码解决)
// 密码编码:PasswordEncoder
// 在spring security 5.0+新增了很多的加密方法
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// 这些数据应该从数据库里读取,使用jdbcAuthentication()
// 目前方式是在内存中读取
auth.inMemoryAuthentication()
.passwordEncoder(new BCryptPasswordEncoder())
.withUser("user1").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1")
.and()
.withUser("user2").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1", "vip2")
.and()
.withUser("user3").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1", "vip2", "vip3");
}
}
登录权限账户
登录user1代表能看到vip1的内容
登录user2代表能看到vip1和vip2的内容
登录user3代表能看到vip1和vip2和vip3的内容
三、注销以及权限控制
1、在index.html实现对应的登录与注销

注意:运行会出现一下结果

这是因为springboot版本太高不支持,最低支持2.0.9.RELEASE版本

启动项目Springboot06SecurityApplicationTests会报错,修改下即可,因为降低了版本对应的导入也不相同

启动项目

然后登录,可以查看到对应的注销按钮和用户名

点击注销,成功回到首页,可以看到对应的用户名也清除掉了

再来看看实现的根据用户权限展示相对应的页面,展示我们用user2用户
大家看到只有vip1和vip2的页面
因为User2的权限就是vip1和vip2

四、注销以及权限控制
现在的情况,我们只要登录之后,关闭浏览器,再登录,就会让我们重新登录,但是很多网站的情况,就是有一个记住密码的功能,这个该如何实现呢?很简单
1、开启记住我功能:只需一行代码
http.rememberMe().rememberMeParameter("remember");
前端接收:
默认保存两周
我们再次启动项目测试一下,发现登录页多了一个记住我功能,我们登录之后关闭 浏览器,然后重新打开浏览器访问,发现用户依旧存在!
2、定制登录页
现在这个登录页面都是spring security 默认的,怎么样可以使用我们自己写的Login界面呢?
在刚才的登录页配置后面指定 login


启动测试:


注意坑:前端登录页面传的参数时默认的username,password,
如果要传递不一样的,要配置接收前端参数
可以根据前端的name进行设置

重启项目测试即可:


本文介绍如何使用SpringSecurity搭建安全环境,包括用户认证与授权、自定义登录页面及实现记住我功能等。



3万+





