1、搭建Security的环境,添加pom,xml相关依赖 Springboot版本号选择:2.3.0.RESEASE
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
2、添加静态资源文件和页面
3、配置application.yml
spring:
thymeleaf:
cache: false
4、测试页面跳转的IndexController类
@Controller
public class IndexController {
@RequestMapping({"/","/index"})
public String index(){
return "index";
}
@RequestMapping(value = "/toLogin")
public String toLogin() {
return "views/login";
}
@RequestMapping(value = "/level1/{id}")
public String level1(@PathVariable("id") Integer id) {
return "views/level1/" + id;
}
@RequestMapping(value = "/level2/{id}")
public String level2(@PathVariable("id") Integer id) {
return "views/level2/" + id;
}
@RequestMapping(value = "/level3/{id}")
public String level3(@PathVariable("id") Integer id) {
return "views/level3/" + id;
}
}
5、引入Security的依赖做权限控制
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
6、编写SpringSecurity的配置类
@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");
http.formLogin();
}
//认证
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("admin").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
.and()
.withUser("kuangsheng").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
.and()
.withUser("edwin").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");
}
}