在web开发中,安全第一位!过滤器,拦截器…
安全框架:shiro、SpringSecurity:很像,除了类不一样,名字不一样
认证、授权(vip1,vip2,vip3)
Spring Security 是一个功能强大且高度可定制的身份验证和访问控制框架。它是保护基于 Spring 的应用程序的事实标准。
- 功能权限
- 访问权限
- 菜单权限
- …过滤器,拦截器:大量的原生代码,冗余
记住几个类
- WebSecurityConfigurerAdaper :自定义Security策略
- AuthenticationManangerBuilder :自定义认证策略
- @EnableWebSecurity:开启WebSecurity模式,@EnableXXX开启某个功能
1、使用thymeleaf
在pom.xml中导入thymeleaf依赖
org.springframework.boot spring-boot-starter-thymeleaf
在application.properties中关闭缓存
spring.thymeleaf.cache=false
2、搭建环境写controller层
@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;
}
}
3、导入依赖
org.springframework.boot
spring-boot-starter-security
4、自定义一个配置类
@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");
//没有权限默认会到登录页面 ,需要开启登录的页面
// /login
http.formLogin();
}
//认证 ,springboot 2.1.x 可以直接使用
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//这些数据正常应该从数据库中读
//密码编码 PasswordEncoder
//在SpringSecurity 5.0+ 新增了很多加密方法
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("zz").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
.and()
.withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
.and()
.withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
}
}
5、完善注销功能
前端页面在index.html页面中增添 注销按钮
6、完善用户权限,通过thymeleaf整合SpringSecurity实现用户权限判断
6-1、导入依赖
org.thymeleaf.extras
thymeleaf-extras-springsecurity4
3.0.4.RELEASE
6-2、在html页面中引入名称空间
xmlns:sec="http://www.thymeleaf.org/extras/spring-security"
6-3、修改前端页面
如果有vip1的权限,就显示Level 1,以此类推…
菜单根据用户权限动态显示的实现
7、开启记住我功能
//定制登录页
http.formLogin().loginPage("/tologin");
//开启记住我功能
http.rememberMe().rememberMeParameter("remember");



