認識SpringSecurity
Spring Security 是針對Spring項目的安全框架,也是Spring Boot底層安全模塊默認的技術選型,他可以實現強大的Web安全控制,對於安全控制,我們僅需要引入 spring-boot-starter-security 模塊,進行少量的配置,即可實現強大的安全管理!
記住幾個類:
-
WebSecurityConfigurerAdapter:自定義Security策略
-
AuthenticationManagerBuilder:自定義認證策略
-
@EnableWebSecurity:開啟WebSecurity模式
Spring Security的兩個主要目標是 “認證” 和 “授權”(訪問控制)。
“認證”(Authentication)
身份驗證是關於驗證您的憑據,如用戶名/用戶ID和密碼,以驗證您的身份。
身份驗證通常通過用戶名和密碼完成,有時與身份驗證因素結合使用。
“授權” (Authorization)
授權發生在系統成功驗證您的身份后,最終會授予您訪問資源(如信息,文件,數據庫,資金,位置,幾乎任何內容)的完全權限。
這個概念是通用的,而不是只在Spring Security 中存在。
認證和授權
目前,我們的測試環境,是誰都可以訪問的,我們使用 Spring Security 增加上認證和授權的功能
1、引入 Spring Security 模塊
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
2、編寫 Spring Security 配置類
參考官網:https://spring.io/projects/spring-security
查看我們自己項目中的版本,找到對應的幫助文檔:
https://docs.spring.io/spring-security/site/docs/current/reference/html5/
3、編寫基礎配置類、定制請求的授權規則
@Override protected void configure(HttpSecurity http) throws Exception { // 定制請求的授權規則 http.authorizeRequests().antMatchers("/").permitAll() .antMatchers("/level1/**").hasRole("vip1") // 首頁所有人可以訪問
.antMatchers("/level2/**").hasRole("vip2")
.antMatchers("/level3/**").hasRole("vip3"); }
4、測試一下:發現除了首頁都進不去了!因為我們目前沒有登錄的角色,因為請求需要登錄的角色擁有對應的權限才可以!
5、在configure()方法中加入以下配置,開啟自動配置的登錄功能!
// 開啟自動配置的登錄功能 // /login 請求來到登錄頁 // /login?error 重定向到這里表示登錄失敗 http.formLogin();
6、測試一下:發現,沒有權限的時候,會跳轉到登錄的頁面!
7、查看剛才登錄頁的注釋信息;
我們可以定義認證規則,重寫configure(AuthenticationManagerBuilder auth)方法
//定義認證規則 @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { //在內存中定義,也可以在jdbc中去拿.... auth.inMemoryAuthentication() .withUser("admin").password("123456").roles("vip2","vip3") .and() .withUser("root").password("123456").roles("vip1","vip2","vip3") .and() .withUser("guest").password("123456").roles("vip1","vip2"); }
8、使用這些賬號登錄進行測試!會報錯!
There is no PasswordEncoder mapped for the id “null”
9、原因,我們要將前端傳過來的密碼進行某種方式加密,否則就無法登錄,修改代碼
//定義認證規則 @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { //在內存中定義,也可以在jdbc中去拿.... //Spring security 5.0中新增了多種加密方式,也改變了密碼的格式。 //要想我們的項目還能夠正常登陸,需要修改一下configure中的代碼。我們要將前端傳過來的密碼進行某種方式加密 //spring security 官方推薦的是使用bcrypt加密方式。 auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder()) .withUser("kuangshen").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3") .and() .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3") .and() .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2"); }
10、測試,發現,登錄成功,並且每個角色只能訪問自己認證下的規則!
權限控制和注銷
1、開啟自動配置的注銷的功能
//定制請求的授權規則 @Override protected void configure(HttpSecurity http) throws Exception { //.... //開啟自動配置的注銷的功能 http.logout(); }
2、我們在前端,增加一個注銷的按鈕,index.html 導航欄中
<a class="item" th:href="@{/logout}"> <i class="address card icon"></i> 注銷 </a>
3、我們可以去測試一下,登錄成功后點擊注銷,發現注銷完畢會跳轉到登錄頁面!
4、但是,我們想讓他注銷成功后,依舊可以跳轉到首頁,該怎么處理呢?
// .logoutSuccessUrl("/"); 注銷成功來到首頁 http.logout().logoutSuccessUrl("/");
5、測試,注銷完畢后,發現跳轉到首頁OK
6、我們現在又來一個需求:用戶沒有登錄的時候,導航欄上只顯示登錄按鈕,用戶登錄之后,導航欄可以顯示登錄的用戶信息及注銷按鈕!還有就是,比如admin這個用戶,它只有 vip2,vip3功能,那么登錄則只顯示這兩個功能,而vip1的功能菜單不顯示!這個就是真實的網站情況了!該如何做呢?
我們需要結合thymeleaf中的一些功能
sec:authorize="isAuthenticated()":是否認證登錄!來顯示不同的頁面
Maven依賴:
<!-- https://mvnrepository.com/artifact/org.thymeleaf.extras/thymeleaf-extras-springsecurity4 --> <dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-springsecurity5</artifactId> <version>3.0.4.RELEASE</version> </dependency>
7、修改我們的 前端頁面
導入命名空間
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity5"
修改導航欄,增加認證判斷
<!--登錄注銷--> <div class="right menu"> <!--如果未登錄--> <div sec:authorize="!isAuthenticated()"> <a class="item" th:href="@{/login}"> <i class="address card icon"></i> 登錄 </a> </div> <!--如果已登錄--> <div sec:authorize="isAuthenticated()"> <a class="item"> <i class="address card icon"></i> 用戶名:<span sec:authentication="principal.username"></span> 角色:<span sec:authentication="principal.authorities"></span> </a> </div> <div sec:authorize="isAuthenticated()"> <a class="item" th:href="@{/logout}"> <i class="address card icon"></i> 注銷 </a> </div> </div>
8、重啟測試,我們可以登錄試試看,登錄成功后確實,顯示了我們想要的頁面;
9、如果注銷404了,就是因為它默認防止csrf跨站請求偽造,因為會產生安全問題,我們可以將請求改為post表單提交,或者在spring security中關閉csrf功能;我們試試:在 配置中增加 http.csrf().disable();
http.csrf().disable();//關閉csrf功能:跨站請求偽造,默認只能通過post方式提交logout請求 http.logout().logoutSuccessUrl("/");
記住密碼功能
現在的情況,我們只要登錄之后,關閉瀏覽器,再登錄,就會讓我們重新登錄,但是很多網站的情況,就是有一個記住密碼的功能,這個該如何實現呢?很簡單
1、開啟記住我功能
//定制請求的授權規則 @Override protected void configure(HttpSecurity http) throws Exception { //。。。。。。。。。。。 //記住密碼功能
http.rememberMe();
}
2、我們再次啟動項目測試一下,發現登錄頁多了一個記住我功能,我們登錄之后關閉 瀏覽器,然后重新打開瀏覽器訪問,發現用戶依舊存在!
思考:如何實現的呢?其實非常簡單,我們可以查看瀏覽器的cookie,登錄成功后,將cookie發送給瀏覽器保存,以后登錄帶上這個cookie,只要通過檢查就可以免登錄了。如果點擊注銷,則會刪除這個cookie!
3、我們點擊注銷的時候,可以發現,spring security 幫我們自動刪除了這個 cookie。