1.spring security的環境搭建
首先新建一個springboot項目,只夠選web中的spring web依賴
然后在pom.xml導入相關依賴
<!--thymeleaf模塊-->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
然后導入素材
項目所需要的素材我放到我的github上,需要的自取
導入資源並刪掉多余的東西,如圖
在application.properties配置文件里關掉thymeleaf模板緩存,以方便進行我們的測試
#關掉thymeleaf模板緩存,以方便進行我們的測試
spring.thymeleaf.cache=false
緊接着新建一個controller包,在包下編寫一個controller類RouterController,作為我們的路由轉發
完整代碼如下:
package cn.dzp.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class RouterController {
//使得訪問/,/index,/index.html都能跳到主頁
@RequestMapping({"/","/index","/index.html"})
public String index(){
return "index";
}
@RequestMapping("/toLogin")
public String toLogin(){
return "views/login";
}
//實現對level的三個頁面的跳轉,下面也是如此
@RequestMapping("/level1/{id}")
public String level1(@PathVariable("id") int id){
return "views/level1/"+id;
}
@RequestMapping("/level2/{id}")
public String level2(@PathVariable("id") int id){
return "views/level2/"+id;
}
@RequestMapping("/level3/{id}")
public String level3(@PathVariable("id") int id){
return "views/level3/"+id;
}
}
啟動項目查看效果
點擊對應的level等級頁面也能跳轉
2.用戶認證和授權
"認證"(Authentication)
"授權"(Authorization)
這兩個概念是通用的,而不是只在Spring security中存在
導入security依賴
<!--security-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
創建一個config包,編寫一個SecurityConfig類
完整代碼如下:
package cn.dzp.config;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
//鏈式編程
// 授權
@Override
protected void configure(HttpSecurity http) throws Exception {
// 首頁所有人可以訪問,功能頁只有對應權限的人才能訪問
// 請求授權的規則
http.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/level1/**").hasRole("level1")
.antMatchers("/level2/**").hasRole("level2")
.antMatchers("/level3/**").hasRole("level3");
// 沒有權限默認會跳到登錄頁面,需要開啟登錄的頁面
http.formLogin();
// 防止網站攻擊:get;post
http.csrf().disable();//關閉csrf(跨站請求偽造)功能,登出失敗可能產生的原因
// 開啟注銷功能
http.logout().logoutSuccessUrl("/");
}
// 認證,springboot 2.1.x可以直接使用,其他版本會報錯(或者采用下面的密碼編碼解決)
// 密碼編碼:PasswordEncoder
// 在spring security 5.0+新增了很多的加密方法
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// 這些數據應該從數據庫里讀取,使用jdbcAuthentication()
// 目前方式是在內存中讀取
auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
.withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("level1")
.and()
.withUser("dzp").password(new BCryptPasswordEncoder().encode("456789")).roles("level1","level2")
.and()
.withUser("root").password(new BCryptPasswordEncoder().encode("root")).roles("level3","level2","level1");
}
}
登錄最高權限賬戶
3.注銷以及權限控制
由於本次使用到了thymeleaf與spring security的整合,所以需要導入依賴
<!-- security與themeleaf整合包 -->
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity4</artifactId>
<version>3.0.4.RELEASE</version>
</dependency>
並且要在index.html中導入對應的約束
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4"
在index.html實現對應的登錄與注銷
注意:運行會出現一下結果
這是因為springboot版本太高不支持,最低支持2.0.9.RELEASE版本
啟動項目Springboot06SecurityApplicationTests會報錯,修改下即可,因為降低了版本對應的導入也不相同
啟動項目
然后登錄,可以查看到對應的注銷按鈕和用戶名
點擊注銷,成功回到首頁,可以看到對應的用戶名也清除掉了
再來看看實現的根據用戶權限展示相對應的頁面,展示我們用dzp用戶更清楚
也成功實現
4.記住我以及首頁定制
開啟記住我功能(cookie的實現)
啟動項目試試
雖然不好看,但是已經看到實現了remember me的功能
開啟記住我登錄root用戶在關掉瀏覽器重新打開檢查是否還存在root
可以看到再次打開有了remember me的cookie,說明成功
remember me默認保存的世界為14天==兩周,如果清掉cookie,主頁則會自動跳到首頁(測試時間為2021.5.11)
自己定義登錄頁面
重啟項目測試,確實跳轉成功
注意坑:前端登錄頁面傳的參數可能和默認的username,password不一樣,則會傳遞參數失敗,可以根據前端的name進行設置
http.formLogin().loginPage("/toLogin").usernameParameter("user").passwordParameter("pwd").loginProcessingUrl("/login");
http.rememberMe().rememberMeParameter("remember");
重啟項目測試
成功登錄
到此關於security所有功能實現!