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"); } }