Spring Security
一、Spring Security是什么
按照官网解释,Spring Security是一个功能强大且高度可定制的身份验证和访问控制框架。提供了完善的认证机制和方法级的授权功能。是一款非常优秀的权限管理框架。它的核心是一组过滤器链,不同的功能经由不同的过滤器。参见 Spring Security 中文手册 。
二、Spring Security 核心模块
认证(Authentication)
验证某个用户是否为系统中的合法主体,也就是说用户能否访问该系统
授权(Authorization)
验证某个用户是否有权限执行某个操作
三、整合Springboot
1、导入security依赖
可以在创建 Springboot项目的时候 ,勾选spring security 依赖;
也可以手动导入
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2、编写前后端页面跳转代码
后端controller
@Controller
public class RouteController {
//使得访问/,/index,/index.html都能跳到主页
@RequestMapping({"/","/index","/index.html"})
public String index(){
return "index";
}
@RequestMapping("/toLogin")
public String toLogin(){
return "views/login";
}
//实现对level的三个页面的跳转,下面也是如此
@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;
}
}
前端页面
参见项目
前后端整合需要导入对应的依赖(security与themeleaf整合包)
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
</dependency>
3、配置config
@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();
// 自定义个login页面
http.formLogin().loginPage("/toLogin").usernameParameter("username").loginProcessingUrl("password").loginProcessingUrl("/usr/login");
// 防止网站攻击:get;post
http.csrf().disable();//关闭csrf(跨站请求伪造)功能,登出失败可能产生的原因
// 开启注销功能
http.logout().logoutSuccessUrl("/");
// 开启记住我功能
// http.rememberMe();
http.rememberMe().rememberMeParameter("remember");
}
// 认证,springboot 2.1.x可以直接使用,其他版本会报错(或者采用下面的密码编码解决)
// 密码编码:PasswordEncoder
// 在spring security 5.0+新增了很多的加密方法
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// 这些数据应该从数据库里读取,使用jdbcAuthentication()
// 目前方式是在内存中读取
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("level1")
.and()
.withUser("dzp").password(new BCryptPasswordEncoder().encode("456789")).roles("level1","level2")
.and()
.withUser("root").password(new BCryptPasswordEncoder().encode("root")).roles("level3","level2","level1");
}
}
4、测试
1、登录页跳转;没有权限的用户默认跳转登录页
2、用户权限登录;不同用户访问 level 权限不同
3、用户名展示;用户登录后展示用户名
4、记住我;关闭浏览器,重新打开页面,用户是否处于登录状态
5、用户注销;用户退出后,是否显示用户名