SpringSecurity權限控制的簡單實作
1.首先建立一個SpringBoot工程,并匯入相關的依賴
<!--security-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!--web-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--thymeleaf-->
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
在template檔案夾下面放入三個等級的頁面,以便后面驗證權限
如下:

創建Controller檔案夾,隨后在內部創建一個路由類,方便分流

/**
* @author 蒲成偉
* @create 2021-07-31-15:11
*/
@Controller
public class PageRutoer {
@GetMapping("/Leavle1/{id}")
public String VIP1(@PathVariable("id") Integer id){
System.out.println("id = " + id);
return "/leavel1/hello"+id;
}
@GetMapping("/Leavle2/{id}")
public String VIP2(@PathVariable("id") Integer id){
System.out.println("id = " + id);
return "/leavel2/hello"+id;
}
@GetMapping("/Leavle3/{id}")
public String VIP3(@PathVariable("id") Integer id){
System.out.println("id = " + id);
return "/leavel3/hello"+id;
}
}
隨后繼續創建Security配置類
/**
* @author 蒲成偉
* @create 2021-07-31-15:00
*/
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
//根據請求路徑的不同,將頁面分成三個等級,第一級所有人員均可以訪問
//二級頁面需要vip2級可以訪問,以此類推
http.authorizeRequests()
.antMatchers("/Leavle1/**").permitAll()
.antMatchers("/Leavle2/**").hasRole("vip2")
.antMatchers("/Leavle3/**").hasRole("vip3");
http.formLogin();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//設定用戶權限,按正規的本來需要從資料庫中獲取這些資訊,這里為了方便就直接定了用戶資訊和賬號權限
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("puchengwei").password((new BCryptPasswordEncoder().encode("123456"))).roles("vip2")
.and()
.withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3");
}
}
至此配置完畢可以啟動應用程式驗證
不登陸時,訪問一級頁面成功

訪問二級頁面失敗,并重定向到登錄界面,

繼續輸入剛剛設定的用戶資訊:登錄自己設定的root用戶

頁面請求成功

頁面三請求成功

至此驗證成功!!!!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/291286.html
標籤:其他
上一篇:Web安全——SQL注入漏洞
下一篇:常見網路攻擊掃盲~
