前言
主要是根据尚硅谷的SpringBoot整合版视频来进行学习
本次项目中SpringBoot的版本是2.4.1
SpringSecurity的版本是5.4.2
controller层的代码如下:
@Controller
public class KungfuController {
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;
}
}
根据此可大致得出资源文件的路径
一、SpringSecurity是什么?
安全框架:轻量级的shiro、较为重量级的SpringSecurity
引入官方的原话:Spring Security是一个提供身份验证,授权和保护以防止常见攻击的框架。凭借对命令式和响应式应用程序的一流支持,它是用于保护基于Spring的应用程序的事实上的标准
安全框架的基本功能:认证和授权(访问控制)
二、使用步骤
1.引入库:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2.编写一个配置类继承WebSecurityConfigurerAdapter
@EnableWebSecurity注解已声明@Configuration配置类,故子类无需声明该类为配置类
重写protected void configure(HttpSecurity http)方法定制请求的授权规则:即定义客户端发送某请求后,授权请求authorizeRequests();
扫描二维码关注公众号,回复:
12595799 查看本文章
antMatchers("/")设置匹配规则,代表所有请求
.antMatchers("/level1/**"),代表/level1/下的所有请求。
@EnableWebSecurity
public class MySecurityConfig 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");
// 开启自动配置登录功能
// 1./login来到登录页
// 2.重定向到/login?error表示登录失败
// 3.更多详细规定
http.formLogin();
// 开启自动配置的注销功能
// 1.访问/logout 表示用户注销,清空session
// 2.注销成功会返回 /login?logout 页面
http.logout().logoutSuccessUrl("/");
}
// 定义认证规则
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.passwordEncoder(new BCryptPasswordEncoder()).withUser("zhangsan").password(new BCryptPasswordEncoder().encode("123456")).roles("VIP1","VIP2")
.and()
.passwordEncoder(new BCryptPasswordEncoder()).withUser("lisi").password(new BCryptPasswordEncoder().encode("123456")).roles("VIP2","VIP3")
.and()
.passwordEncoder(new BCryptPasswordEncoder()).withUser("wangwu").password(new BCryptPasswordEncoder().encode("123456")).roles("VIP1","VIP3");
}
}
3.效果:
如若未进行登录,点击任何操作,都是跳转至Spring自己提供的登录页面。