網(wǎng)絡(luò)科技有限公司的簡(jiǎn)介高州網(wǎng)站seo
一、前言
Spring Security已經(jīng)更新到了6.x,通過(guò)本專欄記錄以下Spring Security6學(xué)習(xí)過(guò)程,當(dāng)然大家可參考Spring Security5專欄對(duì)比學(xué)習(xí)
Spring Security5專欄地址:security5
Spring Security是spring家族產(chǎn)品中的一個(gè)安全框架,核心功能包括用戶認(rèn)證(Authentication)和用戶授權(quán)(Authorization)兩部分。
用戶認(rèn)證:驗(yàn)證某個(gè)用戶是否為系統(tǒng)中的合法主體,也就是說(shuō)用戶能否訪問(wèn)該系統(tǒng)。用戶認(rèn)證一般要求用戶提供用戶名和密碼。系統(tǒng)通過(guò)校驗(yàn)用戶名和密碼來(lái)完成認(rèn)證過(guò)程。
用戶授權(quán):指的是驗(yàn)證某個(gè)用戶是否有權(quán)限執(zhí)行某個(gè)操作。在一個(gè)系統(tǒng)中,不同用戶所具有的權(quán)限是不同的。比如對(duì)一個(gè)文件來(lái)說(shuō),有的用戶只能進(jìn)行讀取,而有的用戶可以進(jìn)行修改。一般來(lái)說(shuō),系統(tǒng)會(huì)為不同的用戶分配不同的角色,而每個(gè)角色則對(duì)應(yīng)一系列的權(quán)限。就是所謂的RBAC系統(tǒng)。
權(quán)限認(rèn)證框架類似的還有shiro、以及國(guó)產(chǎn)Sa-Token,可以類比學(xué)習(xí)
?
二、項(xiàng)目創(chuàng)建
創(chuàng)建一個(gè)springboot項(xiàng)目,jdk版本17、boot版本3.1.2、security版本6
pom.xml如下
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>3.1.2</version><relativePath/></parent><groupId>com.demo</groupId><artifactId>security6</artifactId><version>0.0.1-SNAPSHOT</version><name>security6</name><description>security6</description><properties><java.version>17</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>
自定義一個(gè)controller
@RestController
public class IndexController {@RequestMapping("index")public String index(){return "index";}}
啟動(dòng)項(xiàng)目訪問(wèn)index路徑,可以看到securit已經(jīng)攔截請(qǐng)求
?使用控制臺(tái)提供的默認(rèn)密碼即可登錄
?實(shí)際是security底層有個(gè)攔截器,攔截判斷是否登錄,沒(méi)有的話會(huì)跳轉(zhuǎn)到登錄login頁(yè)面
當(dāng)然上面的用戶名和密碼可以通過(guò)配置改變,如下
spring.security.user.name=admin
spring.security.user.password=12345
三、前后端不分離項(xiàng)目自定義相關(guān)配置
首先引入前后端不分離頁(yè)面模板引擎Thymeleaf依賴
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
讓后resources/templates下創(chuàng)建登錄頁(yè)面和首頁(yè)
登錄頁(yè)面login.html
<!DOCTYPE html>
<html lang="en" xmlns:th="https://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>登錄</title>
</head>
<body>
<h1>歡迎登錄</h1>
<form th:action="@{/login}" method="post">用戶名:<input type="text" name="username">密碼: <input type="text" name="password"><input type="submit" value="登錄">
</form>
</body>
</html>
首頁(yè)頁(yè)面index.html
<!DOCTYPE html>
<html lang="en" xmlns:th="https://www.thymeleaf.org">
<head><meta charset="UTF-8"><title>首頁(yè)</title>
</head>
<body>
<h1>歡迎使用本系統(tǒng)</h1>
注意:security退出是一個(gè)post請(qǐng)求
<form method="post" th:action="@{/logout}"><input type="submit" value="退出">
</form>
</body>
</html>
controller類
@Controller
public class IndexController {@RequestMapping("info")@ResponseBodypublic String info(){return "歡迎使用本系統(tǒng)!";}//前往index頁(yè)面@RequestMapping("index")public String index(){return "index";}//前往登錄頁(yè)面@RequestMapping("toLoginPage")public String login(){return "login";}
}
和5的使用方法一樣,修改security相關(guān)配置還是通過(guò)自定義配置類,如下
/*** 5版本只需@Configuration一個(gè)注解,不需要@EnableWebSecurity,* 6需要同時(shí)引入,并且5是需要extends WebSecurityConfigurerAdapter類*/
@Configuration
@EnableWebSecurity
public class MySecurityConfig {/*** 5版本是override 方法: configure(HttpSecurity http),6是下面bean*/@Beanpublic SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception{//authorizeHttpRequests:針對(duì)http請(qǐng)求進(jìn)行授權(quán)認(rèn)證,定義不需要認(rèn)證就能的資源路徑,如infohttp.authorizeHttpRequests(authorizeHttpRequests->authorizeHttpRequests.requestMatchers("/info").permitAll().anyRequest().authenticated());/**登錄表單配置* loginPage:登錄頁(yè)面請(qǐng)求地址* loginProcessingUrl:登錄接口 過(guò)濾器* successForwardUrl:登錄成功響應(yīng)地址* failureForwardUrl:登錄失敗響應(yīng)地址*/http.formLogin(formLogin->formLogin.loginPage("/toLoginPage").permitAll().loginProcessingUrl("/login").successForwardUrl("/index").failureForwardUrl("/toLoginPage"));//關(guān)閉crsf 跨域漏洞防御http.csrf(withDefaults());//相當(dāng)于 http.csrf(Customizer.withDefaults());或者h(yuǎn)ttp.csrf(crsf->crsf.disable());//退出http.logout(logout -> logout.invalidateHttpSession(true));return http.build();}
}
四、前后端分離項(xiàng)目登錄
對(duì)于前后端分離項(xiàng)目,我們不再需要模板引擎thymeleaf依賴以及index,login頁(yè)面,核心配置類如下
@Configuration
@EnableWebSecurity
public class MySecurityConfig {@Beanpublic SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception{//不需要認(rèn)證的請(qǐng)求http.authorizeHttpRequests(authorizeHttpRequests->authorizeHttpRequests.requestMatchers("/info").permitAll().anyRequest().authenticated());//登錄http.formLogin(formLogin -> formLogin//登錄接口.loginProcessingUrl("/login")//登錄成功響應(yīng),直接使用接口表達(dá)式,也可和5版本一樣子自定義類.successHandler((request,response,authentication)->{//這里可以根據(jù)自己業(yè)務(wù)封裝響應(yīng)體response.setContentType("text/html;charset=UTF-8");response.getWriter().write("ok");System.out.println(authentication.getCredentials()+"--"+authentication.getPrincipal()+"--"+authentication.getAuthorities());})//登錄失敗響應(yīng).failureHandler((request,response,authenticationException) ->{response.setContentType("text/html;charset=UTF-8");response.getWriter().write("ok");authenticationException.printStackTrace();}));//關(guān)閉crsf,跨域漏洞防御http.csrf(withDefaults());//跨域攔截http.cors(withDefaults());return http.build();}
}