Spring Security(一):Spring Security 介紹及身份認證方式


Spring Security 介紹

  1. Spring Security 是基於 Spring 的身份認證(Authentication)和用戶授權(Authorization)框架,提供了一套 Web 應用安全性的完整解決方案。其中核心技術使用了 Servlet 過濾器、IOC 和 AOP 等。
  2. 什么是身份認證
    身份認證指的是用戶去訪問系統資源時,系統要求驗證用戶的身份信息,用戶身份合法才訪問對應資源。
    常見的身份認證一般要求用戶提供用戶名和密碼。系統通過校驗用戶名和密碼來完成認證過程。
  3. 什么是用戶授權
    當身份認證通過后,去訪問系統的資源,系統會判斷用戶是否擁有訪問該資源的權限,只允許訪問有權限的系統資源,沒有權限的資源將無法訪問,這個過程叫用戶授權。
    比如 會員管理模塊有增刪改查功能,有的用戶只能進行查詢,而有的用戶可以進行修改、刪除。一般來說,系統會為不同的用戶分配不同的角色,而每個角色則對應一系列的權限

SpringSecurity身份認證方式:

  • HttpBasic 是彈窗認證方式。
  • HttpForm 是表單認證方式。

創建安全配置類SpringSecurityConfig並且繼承WebSecurityConfigurerAdapter作為安全控制中心, 用於實現身份認證與授權配置功能,此類需要加上@EnableWebSecurity證明 啟動springSecurity過濾鏈功能,需要重寫兩個方法

/**
   身份認證過濾器
2. 認證信息提供方式(用戶名,密碼,當前用戶的資源權限)
3. 可采的內存存儲方式,也可采用數據庫方式等。
*/
configure(AuthenticationManagerBuilder auth);

/**
 資源權限配置(過濾器鏈)
4. 攔截哪些資源
5. 資源所對應的角色權限
 3. 定義認證方式 httpbasic  httpform
6. 定制登錄頁面,登錄請求地址,錯誤處理方式
7. 自定義 springsecurity 過濾器等
*/
configure(HttpSecurity http)

 

1.HttpBasic認證方式:

/**
     * 資源權限配置(過濾器鏈):
     * 1、被攔截的資源
     * 2、資源所對應的角色權限
     * 3、定義認證方式:httpBasic 、httpForm
     * 4、定制登錄頁面、登錄請求地址、錯誤處理方式
     * 5、自定義 spring security 過濾器
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.httpBasic()//采用httpBasic 認證方式
                .and()
                .authorizeRequests()//認證請求
                .anyRequest().authenticated();// 所有進入應用的HTTP請求都要進行認證
    }

1.使用HttpBasic 認證方式

1.1使用security默認的賬號和密碼,賬號為user 密碼  springboot啟動日志中的Using generated security password: 9be0927b-b0bb-4253-92a6-d57954e5da87

 

 

 

1..2,使用內存自定義用戶名和密碼,

Logger logger= LoggerFactory.getLogger(SpringSecurityConfig.class);


    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder(){
        // 加密存儲   明文+隨機鹽值
        return  new BCryptPasswordEncoder();
    }


    /**
     * 認證管理器:
     * 1、認證信息提供方式(用戶名、密碼、當前用戶的資源權限)
     * 2、可采用內存存儲方式,也可能采用數據庫方式等
     *
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // 存儲的密碼必須是加密后的 不然會報錯:There is no PasswordEncoder mapped for the id "null"
        //auth.inMemoryAuthentication().withUser("zcc").password("123").authorities("ADMIN");
        String password=bCryptPasswordEncoder().encode("123");
        logger.info("加密后的密碼:"+password);
        auth.inMemoryAuthentication().withUser("zcc").password(password).authorities("ADMIN");
    }

 

2.使用HttpForm 表單認證方式

 /**
     * 資源權限配置(過濾器鏈):
     * 1、被攔截的資源
     * 2、資源所對應的角色權限
     * 3、定義認證方式:httpBasic 、httpForm
     * 4、定制登錄頁面、登錄請求地址、錯誤處理方式
     * 5、自定義 spring security 過濾器
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //http.httpBasic()//采用httpBasic 認證方式
        http.formLogin()
                .and()
                .authorizeRequests()//認證請求
                .anyRequest().authenticated();// 所有進入應用的HTTP請求都要進行認證
    }

 

 

 

 

3.完整安全配置類代碼:

package com.ytkj.security.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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;

/**
 *  安全配置類作為安全控制中心, 用於實現身份認證與授權配置功能
 */
@Configuration
@EnableWebSecurity //啟動 SpringSecurity 過濾器鏈功能
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    Logger logger= LoggerFactory.getLogger(SpringSecurityConfig.class);


    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder(){
        // 加密存儲   明文+隨機鹽值
        return  new BCryptPasswordEncoder();
    }


    /**
     * 認證管理器:
     * 1、認證信息提供方式(用戶名、密碼、當前用戶的資源權限)
     * 2、可采用內存存儲方式,也可能采用數據庫方式等
     *
     * @param auth
     * @throws Exception
     */
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //基於內存存儲認證信息 存儲的密碼必須是加密后的 不然會報錯:There is no PasswordEncoder mapped for the id "null"
        //auth.inMemoryAuthentication().withUser("zcc").password("123").authorities("ADMIN");
        String password=bCryptPasswordEncoder().encode("123");
        logger.info("加密后的密碼:"+password);
        auth.inMemoryAuthentication().withUser("zcc").password(password).authorities("ADMIN");
    }

    /**
     * 資源權限配置(過濾器鏈):
     * 1、被攔截的資源
     * 2、資源所對應的角色權限
     * 3、定義認證方式:httpBasic 、httpForm
     * 4、定制登錄頁面、登錄請求地址、錯誤處理方式
     * 5、自定義 spring security 過濾器
     *
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //http.httpBasic()//采用httpBasic 認證方式
        http.formLogin()
                .and()
                .authorizeRequests()//認證請求
                .anyRequest().authenticated();// 所有進入應用的HTTP請求都要進行認證
    }
}

 

底層源碼實現:

  spring security采用過濾器鏈實現認證與授權

    1.UsernamePasswordAuthenticationFilter :請求為/login,方式為post  請求中包含用戶名密碼則進行認證,認證成功標記認證成功,否則進入下一個認證過濾器(HTTP form請求方式)

        

 

         

 

         

    2.BasicAuthenticationFilter :請求頭有basic開頭的信息,base64解碼后認證,認證成功則標記認證成功,否則進入下一認證過濾器(前提是使用了httpbasic認證方式,如果使用HTTP form認證方式則不會進入此過濾器)

         

 

         

    3.其他認證過濾器

    4.ExceptionTranslationFilter :捕獲異常處理后續處理

        

 

 

    5.FilterSecurityInterceptor : 認證通過后,根據資源權限配置來判斷當前請求是否可以訪問對應資源。(1 2 3 屬於用戶認證,只屬於第一道門檻,這里會根據 config 中配置的對應權限再次進行鑒權,如果沒有對應的可訪問資源 那就會拋出異常 4 )

    

 完整代碼地址:https://gitee.com/zhechaochao/security-parent.git


免責聲明!

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



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