10、狂神說Springboot整合SpringSecurity


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

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM