Security是什么?
是一个安全框架。可以用来做认证和授权
SpringSecurity环境搭建
1、创建一个新的project
2、导入thymeleaf依赖
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
3、导入静态资源:Spring security教程案例素材(狂神说Java之SpringBoot教程集合版): 狂神SpringBoot教程IDEA版中p34中用到的页面素材,学习Spring security
4、在controller包下,编写RouterController
@Controller
public class RouterController {
@RequestMapping({"/","/index","/index.html"})
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;
}
}
5、显示结果
首页:
登录页:
用户认证和授权
1、导入security的starter
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2、在config包下,编写一个类去继承WebSecurityConfigurerAdapter,并且加上注解@EnableWebSecurity
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//授权
@Override
protected void configure(HttpSecurity http) throws Exception {
//请求授权的规则
http.authorizeHttpRequests()
//首页所有人都可以访问,功能页只有对应权限的人才可以访问
.antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("vip1")
.antMatchers("/level2/**").hasRole("vip2")
.antMatchers("/level3/**").hasRole("vip3");
//没有权限默认会到登录页面,需要开启登录的页面
http.formLogin();
}
//认证
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//这些数据正常应该从数据库中读
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("qiu").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("vip3");
}
}
注销
//开启注销功能,注销成功之后跳到首页
http.logout().logoutSuccessUrl("/");
记住我
前端:
<input type="checkbox" name="remember">记住我
后端:
//开启记住我功能,自定义接受前端传过来的参数
http.rememberMe().rememberMeParameter("remember");
原理是保存了一个cookie和一个session,默认保存14天
定制登录页
http.formLogin().loginPage("/toLogin");