SpringBoot已經為使用者採用預設配置,只需要引入pom依賴就能快速啟動Spring Security。
目的:驗證請求使用者的身份,提供安全存取
優勢:基於Spring,配置方便,減少大量程式碼
內建存取控制方法
permitAll()
表示所符合的URL 任何人都允許存取。authenticated()
表示所符合的 URL 都需要被認證才能存取。anonymous()
表示可以匿名存取符合的 URL 。和permitAll() 效果類似,只是設定為anonymous() 的url 會執行filter 鏈中denyAll()
表示所符合的URL 都不允許被訪問。rememberMe()
被「remember me」的用戶允許訪問這個有點類似於很多網站的十天內免登錄,登陸一次即可記住你,然後未來一段時間不用登入。fullyAuthenticated()
如果使用者不是被 remember me 的,才可以存取。也就是必須一步一步按部就班的登入才行。
角色權限判斷
#hasAuthority(String)
判斷使用者是否具有特定的權限,使用者的權限是在自訂登入邏輯hasAnyAuthority(String ...)
如果使用者擁有給定權限中某一個,就允許存取hasRole(String)
如果使用者俱備給定角色就允許存取。否則出現403hasAnyRole(String ...)
如果使用者俱備給定角色的任一個,就允許被存取-
#hasIpAddress(String)
如果請求是指定的IP 就執行存取。可以透過request.getRemoteAddr() 取得ip 位址
引用Spring Security
Pom 檔案中新增
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
<?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 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <parent> <artifactId>vipsoft-parent</artifactId> <groupId>com.vipsoft.boot</groupId> <version>1.0-SNAPSHOT</version> </parent> <modelVersion>4.0.0</modelVersion> <artifactId>vipsoft-security</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-all</artifactId> <version>5.3.7</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
運行後會自動產生password 預設用戶名稱為: user
預設配置每次都啟動專案都會重新產生密碼,同時使用者名稱和攔截要求也不能自訂,在實際應用程式中往往需要自訂配置,因此接下來對Spring Security進行自訂配置。
配置Spring Security (入門)
同時設定角色訪問權限,其中admin可以存取所有路徑(即/*),user只能存取/user下的所有路徑。 自訂配置類,實現
WebSecurityConfigurerAdapter
接口,
接口中有兩個用到的configure()方法,其中一個配置用戶身份,另一個配置使用者權限:
設定使用者身分的configure()方法:
SecurityConfig
package com.vipsoft.web.config; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; 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; import org.springframework.security.crypto.password.PasswordEncoder; @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class SecurityConfig extends WebSecurityConfigurerAdapter { /** * 配置用户身份的configure()方法 * * @param auth * @throws Exception */ @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { PasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); //简化操作,将用户名和密码存在内存中,后期会存放在数据库、Redis中 auth.inMemoryAuthentication() .passwordEncoder(passwordEncoder) .withUser("admin") .password(passwordEncoder.encode("888")) .roles("ADMIN") .and() .withUser("user") .password(passwordEncoder.encode("666")) .roles("USER"); } /** * 配置用户权限的configure()方法 * @param http * @throws Exception */ @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() //配置拦截的路径、配置哪类角色可以访问该路径 .antMatchers("/user").hasAnyRole("USER") .antMatchers("/*").hasAnyRole("ADMIN") //配置登录界面,可以添加自定义界面, 没添加则用系统默认的界面 .and().formLogin(); } }
新增介面測試用
package com.vipsoft.web.controller; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class DefaultController { @GetMapping("/") @PreAuthorize("hasRole('ADMIN')") public String demo() { return "Welcome"; } @GetMapping("/user/list") @PreAuthorize("hasAnyRole('ADMIN','USER')") public String getUserList() { return "User List"; } @GetMapping("/article/list") @PreAuthorize("hasRole('ADMIN')") public String getArticleList() { return "Article List"; } }#######
以上是SpringBoot SpringSecurity怎麼使用的詳細內容。更多資訊請關注PHP中文網其他相關文章!

Javaremainsagoodlanguageduetoitscontinuousevolutionandrobustecosystem.1)Lambdaexpressionsenhancecodereadabilityandenablefunctionalprogramming.2)Streamsallowforefficientdataprocessing,particularlywithlargedatasets.3)ThemodularsystemintroducedinJava9im

Javaisgreatduetoitsplatformindependence,robustOOPsupport,extensivelibraries,andstrongcommunity.1)PlatformindependenceviaJVMallowscodetorunonvariousplatforms.2)OOPfeatureslikeencapsulation,inheritance,andpolymorphismenablemodularandscalablecode.3)Rich

Java的五大特色是多態性、Lambda表達式、StreamsAPI、泛型和異常處理。 1.多態性讓不同類的對象可以作為共同基類的對象使用。 2.Lambda表達式使代碼更簡潔,特別適合處理集合和流。 3.StreamsAPI高效處理大數據集,支持聲明式操作。 4.泛型提供類型安全和重用性,編譯時捕獲類型錯誤。 5.異常處理幫助優雅處理錯誤,編寫可靠軟件。

java'stopfeatureSnificallyenhanceItsperformanCandScalability.1)對象 - 方向clincipleslike-polymormormormormormormormormormormormorableableflexibleandscalablecode.2)garbageCollectionAutectionAutoctionAutoctionAutoctionAutoctionAutoctionAutoMenateMememorymanateMmanateMmanateMmanagementButCancausElatemention.3)

JVM的核心組件包括ClassLoader、RuntimeDataArea和ExecutionEngine。 1)ClassLoader負責加載、鏈接和初始化類和接口。 2)RuntimeDataArea包含MethodArea、Heap、Stack、PCRegister和NativeMethodStacks。 3)ExecutionEngine由Interpreter、JITCompiler和GarbageCollector組成,負責bytecode的執行和優化。

Java'ssafetyandsecurityarebolsteredby:1)strongtyping,whichpreventstype-relatederrors;2)automaticmemorymanagementviagarbagecollection,reducingmemory-relatedvulnerabilities;3)sandboxing,isolatingcodefromthesystem;and4)robustexceptionhandling,ensuringgr

Javaoffersseveralkeyfeaturesthatenhancecodingskills:1)對象 - 方向 - 方向上的allowslowsmodelowsmodelingreal-worldentities

thejvmisacrucialcomponentthatrunsjavacodebytranslatingitolachine特定結構,影響性能,安全性和便攜性。 1)theclassloaderloader,links andinitializesClasses.2)theexecutionEngineExecutionEngineExecutionEngineExecuteNexeCuteByteCuteByteCuteByTecuteByteCuteByteCuteBytecuteBytecuteByteCoDeinintolachineinstructionsions.3)Memo.3)Memo


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

VSCode Windows 64位元 下載
微軟推出的免費、功能強大的一款IDE編輯器