spring security幾個概念
“認證”(Authentication) 是建立一個他聲明的主體的過程(一個“主體”一般是指用戶,設備或一些可以在你的應用程序中執行動作的其他系統) 。
“授權”(Authorization)指確定一個主體是否允許在你的應用程序執行一個動作的過程。為了抵達需要授權的店,主體的身份已經有認證過程建立。
這個概念是通用的, 而不僅僅在Spring Security中 , 在Shiro中也是一樣的.
Spring Security的 Web&安全幾個關鍵點
1. 登陸/注銷
HttpSecurity配置登陸、注銷功能
2. Thymeleaf提供的SpringSecurity標簽支持
需要引入thymeleaf-extras-springsecurity4
sec:authentication=“name” 獲得當前用戶的用戶名
sec:authorize=“hasRole(‘ADMIN’)” 當前用戶必須擁有ADMIN權限時才會顯示標簽內容
3. remember me
表單添加remember-me的checkbox
配置啟用remember-me功能
4. CSRF(Cross-site request forgery)跨站請求偽造
HttpSecurity啟用csrf功能,會為表單添加_csrf的值,提交攜帶來預防CSRF;
我們僅需引入spring-boot-starter-security模塊,進行少量的配置,即可實現強大的安全管理。
security中幾個重要的類如下:
WebSecurityConfigurerAdapter:自定義Security策略
AuthenticationManagerBuilder:自定義認證策略
@EnableWebSecurity:開啟WebSecurity模式 (在@Controller注解的類上追加)
SpringSecurity在SpringBoot中使用
springsecurity在什么都不配的情況下,默認帳號是user, 密碼在啟動日志中隨機生成uuid,如下形式
2019-06-04 09:44:52.852 INFO 33512 --- [ main] b.a.s.AuthenticationManagerConfiguration :
Using default security password: bc4c813c-b8f9-4cdb-9ca9-b406d3492da9
pom.xml添加依賴
<!--在thymeleaf中使用認證標簽需要的額外依賴--> <dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-springsecurity4</artifactId> <version>3.0.2.RELEASE</version> </dependency>
配置MySecurityConfig.java
官方說明自定義SecurityConfig替換默認配置參考鏈接: https://docs.spring.io/spring-security/site/docs/5.2.0.BUILD-SNAPSHOT/reference/htmlsingle/#oauth2resourceserver-sansboot
protected void configure(HttpSecurity http) { http .authorizeRequests() .anyRequest() .authenticated() .and() .oauth2ResourceServer() .jwt(); }
自定義MySecurityConfig.java
@EnableWebSecurity //該注解本身就包含@Configuration public class MySecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { //super.configure(http); //定制授權規則 http.authorizeRequests().antMatchers("/").permitAll(). antMatchers("/level1/**").hasRole("VIP1"). antMatchers("/level2/**").hasRole("VIP2"). antMatchers("/level3/**").hasRole("VIP3"); } }
配置自動生成的登錄頁
開啟自動配置的 /login 登錄頁面,如果不配置, 那么無授權時會報403 Access is denied錯誤,且頁面也不知道跳哪,因為還沒有開啟自動配置的login登錄頁面
,默認使用的是/login 和 /login?error, 現在改成/userlogin,會經過KungfuController的 @GetMapping("/userlogin")注解的方法.
也可以配置登錄頁及登錄時的帳號密碼字段是什么等.
http.formLogin().loginPage("/login").usernameParameter("username").passwordParameter("password");
配置登出界面
開啟自動配置的注銷功能,默認訪問/logout表示注銷,會清空session及cookie,注銷成功后返回/login?logout頁面
http.logout().logoutSuccessUrl("/");//自定義注銷成功后跳轉到/頁面
配置認證規則
/** * 定義認證規則,管理帳號/密碼 * * @param auth * @throws Exception */ @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { //auth.jdbcAuthentication(); //一般用jdbc //學習用內存認證 auth.inMemoryAuthentication() .withUser("bobo").password("123456").roles("VIP1") .and().withUser("sisi").password("123456").roles("VIP1", "VIP2") .and().withUser("xixi").password("123456").roles("VIP1", "VIP2", "VIP3"); }
在pom.xml中引入thymeleaf依賴的springSecurity標簽的插件
<!--在thymeleaf中使用認證標簽需要的額外依賴--> <dependency> <groupId>org.thymeleaf.extras</groupId> <artifactId>thymeleaf-extras-springsecurity4</artifactId> <version>3.0.2.RELEASE</version> </dependency>
html標簽體中引入security規范
<html xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
thymeleaf中顯示用戶信息
<div sec:authorize="isAuthenticated()"> <h2> 您好 , <span sec:authentication="name"></span> 您的角色是 <span sec:authentication="principal.authorities"></span> </h2> </div>
thymeleaf中顯示判斷是否有權限
<div sec:authorize="hasRole('VIP1')"> <h3>普通武功秘籍</h3> <ul> <li><a th:href="@{/level1/1}">羅漢拳</a></li> <li><a th:href="@{/level1/2}">武當長拳</a></li> <li><a th:href="@{/level1/3}">全真劍法</a></li> </ul> </div>
開啟記住我功能
開啟記住我功能登錄成功,會從服務器返回添加名為remember-me的cookie指令, 以后訪問頁面都會帶上該cookie, 只要服務器通過檢查就可以免登錄了,默認14天后失效
http.rememberMe().rememberMeParameter("remember-me");
此時使用/logout會一並清除名為remember-me的cookie , 因為/logout請求在header頭中攜帶了Max-Age=0參數
自定義登錄頁,使用/userlogin
//默認使用的是/login 和 /login?error, 現在改成/userlogin,會經過KungfuController的 @GetMapping("/userlogin")注解的方法 http.formLogin().loginPage("/userlogin");//.usernameParameter("username").passwordParameter("password");
默認get形式的/login來到登錄頁, post形式的/login用來表單登錄.
當自定義了登錄頁面/userlogin后,那么get形式的/userlogin來到登錄頁, post形式的/userlogin用來表單登錄. 見源碼注釋說明如下:
最終項目結構
核心配置類MySecurityConfig.java內容
package com.example.security.config; 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.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer; @EnableWebSecurity //該注解本身就包含@Configuration public class MySecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { //super.configure(http); //定制授權規則 http.authorizeRequests().antMatchers("/").permitAll(). antMatchers("/level1/**").hasRole("VIP1"). antMatchers("/level2/**").hasRole("VIP2"). antMatchers("/level3/**").hasRole("VIP3"); //參見 HttpSecurity 類的 public FormLoginConfigurer<HttpSecurity> formLogin() 方法注解 //開啟自動配置的 /login 登錄頁面,如果不配置, 那么無授權時會報403 Access is denied錯誤,且頁面也不知道跳哪,因為還沒有開啟自動配置的login登錄頁面 //默認使用的是/login 和 /login?error, 現在改成/userlogin,會經過KungfuController的 @GetMapping("/userlogin")注解的方法 http.formLogin().loginPage("/userlogin");//.usernameParameter("username").passwordParameter("password"); //開啟自動配置的注銷功能,默認訪問/logout表示注銷,會清空session及cookie,注銷成功后返回/login?logout頁面 http.logout().logoutSuccessUrl("/");//自定義注銷成功后跳轉到/頁面 //開啟記住我功能登錄成功,會從服務器返回添加名為remember-me的cookie指令, 以后訪問頁面都會帶上該cookie, 只要服務器通過檢查就可以免登錄了,默認14天后失效 http.rememberMe().rememberMeParameter("remember-me"); } /** * 定義認證規則,管理帳號/密碼 * * @param auth * @throws Exception */ @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { //auth.jdbcAuthentication(); //一般用jdbc //學習用內存認證 auth.inMemoryAuthentication() .withUser("bobo").password("123456").roles("VIP1") .and().withUser("sisi").password("123456").roles("VIP1", "VIP2") .and().withUser("xixi").password("123456").roles("VIP1", "VIP2", "VIP3"); } }
直接關閉所有Security的所有攔截功能
http.headers().frameOptions().disable().and().authorizeRequests().antMatchers("/**", "/login*").permitAll(); // 所有用戶都可以訪問
http.csrf().disable().authorizeRequests().anyRequest().permitAll().and().logout().permitAll(); //禁用security的 csrf功能
SpringSecurity默認是禁止接收POST請求的,而GET是默認可以的,官網給出兩個解決方案:1是發送請求時帶上CSRF的token,2是不推薦的做法(把SpringSecurity的CSRF功能關掉),不然很有可能是get請求正常, 但post請求報403 forbidden
springboot security版本差異
帳號密碼配置差異(親測)
在security 4版本中(springboot1.5中使用), application.yml中簡易帳號密碼配置如下,沒有spring:
security: user: name: bobo password: 123456
而在security 5版本中(springboot2開始使用), application.yml中帳號密碼配置如下, 多了一層spring:
spring: security: user: name: bobo password: 123456
禁用security
pom.xml中如果存在以下依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
啟動時控制台會隨機生成登錄密碼, 打印如下:
Using generated security password: 17718027-34f3-444c-9623-7243038d0af9
請求接口時會跳到登錄頁 Please sign in
禁用spring security兩種方法, 配置類或啟動類上加上如下(二選一)
@EnableAutoConfiguration(exclude = {SecurityAutoConfiguration.class}) 或者 @SpringBootApplication(exclude = {SecurityAutoConfiguration.class })
登錄問題
Spring Security在登錄驗證中增加額外數據(如驗證碼)==>https://www.cnblogs.com/phoenix-smile/p/5666686.html
spring security前台登錄如何傳遞多個參數要后台驗證==>https://bbs.csdn.net/topics/390493958 (在username里用_分割啊哈哈哈)
$$$$$$$$$$spring security controller層實現登陸==>https://blog.csdn.net/qq_34675369/article/details/91499798
我的項目git地址
https://gitee.com/KingBoBo/springboot-05-security
最好的教程
在SpringBoot 中使用Security安全框架==>https://blog.csdn.net/qwe86314/article/details/89509765
相關系列 文章
SpringBoot 整合 oauth2(三)實現 token 認證==>https://www.jianshu.com/p/19059060036b
SpringBoot 整合 Security(一)實現用戶認證並判斷返回json還是view==>https://www.jianshu.com/p/18875c2995f1
SpringBoot 整合 Security(二)實現驗證碼登錄==>https://www.jianshu.com/p/9d08c767b33e