天天看點

SpringBoot內建SpringSecurity、認證和授權、權限控制和登出、結合thymeleaf、記住我功能、定制登入頁SpringBoot內建SpringSecurity實驗環境搭建認識SpringSecurity認證和授權權限控制和登出SpringSecurity結合thymeleaf,同一個頁面不同的權限顯示不同的使用者可操作資訊登入頁 記住我功能定制登入頁完整配置

文章目錄

  • SpringBoot內建SpringSecurity
  • 實驗環境搭建
  • 認識SpringSecurity
  • 認證和授權
  • 權限控制和登出
  • SpringSecurity結合thymeleaf,同一個頁面不同的權限顯示不同的使用者可操作資訊
  • 登入頁 記住我功能
  • 定制登入頁
  • 完整配置

SpringBoot內建SpringSecurity

Spring Security是一個功能強大且高度可定制的身份驗證和通路控制架構。它實際上是保護基于spring的應用程式的标準。

Spring Security 基于 Spring 架構,提供了一套 Web 應用安全性的完整解決方案。

Spring Security是一個架構,側重于為Java應用程式提供身份驗證和授權。

Web 應用的安全性包括使用者認證(Authentication)和使用者授權(Authorization)兩個部分。

使用者認證指的是驗證某個使用者是否為系統中的合法主體,也就是說使用者能否通路該系統。使用者認證一般要求使用者提供使用者名和密碼。

使用者授權指的是驗證某個使用者是否有權限執行某個操作。不同使用者所具有的權限是不同的。

在使用者認證方面,Spring Security 架構支援主流的認證方式,包括 HTTP 基本認證、HTTP 表單驗證、HTTP 摘要認證、OpenID 和 LDAP 等。

在使用者授權方面,Spring Security 提供了基于角色的通路控制和通路控制清單(Access Control List,ACL),可以對應用中的領域對象進行細粒度的控制。

實驗環境搭建

1、建立一個初始的springboot項目web子產品,thymeleaf子產品

2、導入靜态資源

welcome.html
|views
	|level1
		1.html
		2.html
		3.html
    |level2
        1.html
        2.html
        3.html
    |level3
        1.html
        2.html
        3.html
Login.html
           

3、controller跳轉

@Controller
public class RouterController {

   @RequestMapping({"/","/index"})
   public String index(){
       return "index";
  }

   @RequestMapping("/toLogin")
   public String toLogin(){
       return "views/login";
  }

   @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;
  }

}
           

4、測試實驗環境是否OK

認識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

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;

@EnableWebSecurity // 開啟WebSecurity模式
public class SecurityConfig extends WebSecurityConfigurerAdapter {

   @Override
   protected void configure(HttpSecurity http) throws Exception {
       
  }
}
           

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("lyh").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("lyh").password(new BCryptPasswordEncoder().encode("123456")).roles("vip2","vip3")
       .and()
        .withUser("root").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
       .adn()
        .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2");
  
}
           

10、測試,發現,登入成功,并且每個角色隻能通路自己認證下的規則。

權限控制和登出

1、開啟自動配置的登出的功能

//定制請求的授權規則
@Override
protected void configure(HttpSecurity http) throws Exception {
   //....
   //開啟自動配置的登出的功能
      // /logout 登出請求
   http.logout();
}
           

2、我們在前端,增加一個登出的按鈕,index.html 導航欄中

<a class="item" th:href="@{/logout}">
   <i class="address card icon"></i> 登出
</a>
           

3、更多選項

SpringSecurity結合thymeleaf,同一個頁面不同的權限顯示不同的使用者可操作資訊

**需求:**使用者沒有登入的時候,導航欄上隻顯示登入按鈕,使用者登入之後,導航欄可以顯示登入的使用者資訊及登出按鈕。

我們需要結合thymeleaf中的一些功能

1、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>
           

2、修改我們的 前端頁面 導入命名空間

3、修改導航欄,增加認證判斷

<!--登入登出-->
<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>
           

如果登出404了,就是因為它預設防止csrf跨站請求僞造,因為會産生安全問題,我們可以将請求改為post表單送出,或者在spring security中關閉csrf功能;我們試試:在配置中增加

http.csrf().disable();

//定制請求的授權規則
@Override
protected void configure(HttpSecurity http) throws Exception {
   //....
    http.csrf().disable();//關閉csrf功能:跨站請求僞造,預設隻能通過post方式送出logout請求
}

           

需求:角色子產品的功能控制顯示

<!-- sec:authorize="hasRole('vip1')" -->
<div class="column" sec:authorize="hasRole('vip1')">
   <div class="ui raised segment">
       <div class="ui">
           <div class="content">
               <h5 class="content">Level 1</h5>
               <hr>
               <div><a th:href="@{/level1/1}"><i class="bullhorn icon"></i> Level-1-1</a></div>
               <div><a th:href="@{/level1/2}"><i class="bullhorn icon"></i> Level-1-2</a></div>
               <div><a th:href="@{/level1/3}"><i class="bullhorn icon"></i> Level-1-3</a></div>
           </div>
       </div>
   </div>
</div>

<div class="column" sec:authorize="hasRole('vip2')">
   <div class="ui raised segment">
       <div class="ui">
           <div class="content">
               <h5 class="content">Level 2</h5>
               <hr>
               <div><a th:href="@{/level2/1}"><i class="bullhorn icon"></i> Level-2-1</a></div>
               <div><a th:href="@{/level2/2}"><i class="bullhorn icon"></i> Level-2-2</a></div>
               <div><a th:href="@{/level2/3}"><i class="bullhorn icon"></i> Level-2-3</a></div>
           </div>
       </div>
   </div>
</div>

<div class="column" sec:authorize="hasRole('vip3')">
   <div class="ui raised segment">
       <div class="ui">
           <div class="content">
               <h5 class="content">Level 3</h5>
               <hr>
               <div><a th:href="@{/level3/1}"><i class="bullhorn icon"></i> Level-3-1</a></div>
               <div><a th:href="@{/level3/2}"><i class="bullhorn icon"></i> Level-3-2</a></div>
               <div><a th:href="@{/level3/3}"><i class="bullhorn icon"></i> Level-3-3</a></div>
           </div>
       </div>
   </div>
</div>
           

登入頁 記住我功能

我們隻要登入之後,關閉浏覽器,再登入,就會讓我們重新登入,但是很多網站有一個記住密碼的功能。

1、開啟記住我功能

//定制請求的授權規則
@Override
protected void configure(HttpSecurity http) throws Exception {
	//......
   	//記住我
   http.rememberMe();
}
           

2、儲存在cookie中預設14天

3、點選登出spring security 幫我們自動删除這個 cookie

4、結論:登入成功後,将cookie發送給浏覽器儲存,以後登入帶上這個cookie,隻要通過檢查就可以免登入了。如果點選登出,則會删除這個cookie

定制登入頁

現在這個登入頁面都是spring security 預設的,怎麼樣可以使用我們自己寫的Login界面呢?

1、在剛才的登入頁配置後面指定 loginpage

//定制請求的授權規則
@Override
protected void configure(HttpSecurity http) throws Exception {
	//......
	http.formLogin().loginPage("/toLogin");
}
           

2、然後前端也需要指向我們自己定義的 login請求

<a class="item" th:href="@{/toLogin}">
   <i class="address card icon"></i> 登入
</a>
           

3、我們登入,需要将這些資訊發送到哪裡,我們也需要配置login.html 配置送出請求及方式,方式必須為post:

<form th:action="@{/login}" method="post">
   <div class="field">
       <label>Username</label>
       <div class="ui left icon input">
           <input type="text" placeholder="Username" name="username">
           <i class="user icon"></i>
       </div>
   </div>
   <div class="field">
       <label>Password</label>
       <div class="ui left icon input">
           <input type="password" name="password">
           <i class="lock icon"></i>
       </div>
   </div>
   <input type="submit" class="ui blue submit button"/>
</form>
           

4、這個請求送出上來,我們還需要驗證處理,怎麼做呢?我們可以檢視formLogin()方法的源碼。我們配置接收登入的使用者名和密碼的參數。

http.formLogin()
  .usernameParameter("username")
  .passwordParameter("password")
  .loginPage("/toLogin")
  .loginProcessingUrl("/login"); // 登陸表單送出請求
           

5、在登入頁增加記住我的多選框

<input type="checkbox" name="remember"> 記住我
           

6、後端驗證處理

//定制 記住我 的參數!
http.rememberMe().rememberMeParameter("remember");
           

7、測試OK

完整配置

package com.lyh.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("vip1")
      .antMatchers("/level2/**").hasRole("vip2")
      .antMatchers("/level3/**").hasRole("vip3");


       //開啟自動配置的登入功能:如果沒有權限,就會跳轉到登入頁面!
           // /login 請求來到登入頁
           // /login?error 重定向到這裡表示登入失敗
       		http.formLogin()
          .usernameParameter("username")
          .passwordParameter("password")
          .loginPage("/toLogin")
          .loginProcessingUrl("/login"); // 登陸表單送出請求

       //開啟自動配置的登出的功能
           // /logout 登出請求
           // .logoutSuccessUrl("/"); 登出成功來到首頁

       http.csrf().disable();//關閉csrf功能:跨站請求僞造,預設隻能通過post方式送出logout請求
       http.logout().logoutSuccessUrl("/");

       //記住我
       http.rememberMe().rememberMeParameter("remember");
  }

   //定義認證規則
   @Override
   protected void configure(AuthenticationManagerBuilder auth) throws Exception {
       //在記憶體中定義,也可以在jdbc中去拿....
       //Spring security 5.0中新增了多種加密方式,也改變了密碼的格式。
       //要想我們的項目還能夠正常登陸,需要修改一下configure中的代碼。我們要将前端傳過來的密碼進行某種方式加密
       //spring security 官方推薦的是使用bcrypt加密方式。

       auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
              .withUser("lyh").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");
  }
}