springboot學習(七)安全管理 spring security
阿新 • • 發佈:2020-12-20
Spring Security入門
Spring Security 是 Spring 家族中的一個安全管理框架,Spring Boot 對於 Spring Security 提供了 自動化配置方案,可以零配置使用 Spring Security
-
新增依賴,只要加入依賴,專案的所有介面都會被自動保護起來,訪問系統會先需要登入認證
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
預設的使用者名稱為user
,密碼在控制檯,每次啟動專案都會變,對登入的使用者名稱/密碼進行配置,有三種不同的方式:
-
在 application.properties 中進行配置
-
通過 Java 程式碼配置在記憶體中
-
通過 Java 從資料庫中載入
-
使用者名稱密碼配置
-
在 application.properties 中配置
spring.security.user.name=hjy
spring.security.user.password=123456配置完成後,重啟專案,就可以使用這裡配置的使用者名稱/密碼登入了
-
在Java程式碼中配置
建立一個 Spring Security 的配置類,繼承自 WebSecurityConfigurerAdapter 類,使用BCryptPasswordEncoder 進行密碼加密(從 Spring5 開始,強制要求密碼要加密)
Spring Security 中提供了 BCryptPasswordEncoder 密碼編碼工具,可以非常方便的實現密碼的加密加鹽,相同明文加密出來的結果總是不同,這樣就不需要使用者去額外儲存 鹽的欄位了
-
登入配置
對於登入介面,登入成功後的響應,登入失敗後的響應,我們都可以在 WebSecurityConfigurerAdapter 的實現類中進行配置
-