Spring Security 官方介紹 https://spring.io/projects/spring-security#learnjava
Spring Security 目標是解決 「你是誰?」、「你能作什麼?」兩個問題。web
|____spring-security-learn-1 | |____build.gradle | |____src | | |____main | | | |____java | | | |____resources
重點引入 spring-boot-starter-security 依賴項,完整的 gradle 配置以下:spring
plugins { id 'java' id "io.spring.dependency-management" version "1.0.8.RELEASE" } group 'net.txt100.learn' version '1.0' sourceCompatibility = 1.8 apply plugin: 'application' mainClassName = 'net.txt100.learn.springsecurity.base.case1.Case1Application' repositories { maven { url "http://maven.aliyun.com/nexus/content/groups/public" } mavenCentral() } dependencyManagement { imports { mavenBom 'org.springframework.boot:spring-boot-dependencies:2.1.6.RELEASE' } } dependencies { testCompile group: 'junit', name: 'junit', version: '4.12' // spring boot compile group: 'org.springframework.boot', name: 'spring-boot-starter-web' compile group: 'org.springframework.boot', name: 'spring-boot-starter-security' }
package net.txt100.learn.springsecurity.base.case1.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * Title: UserController * Package: net.txt100.learn.springsecurity.base.case1.controller * Creation date: 2019-08-08 * Description: * * @author <a href="me@tonglei.win">Tonglei</a> * @since 1.0 */ @RestController @RequestMapping("/user") public class UserController { @RequestMapping("/all") public String getAllUsers() { return "這是一個被保護的資源 /user/all"; } }
package net.txt100.learn.springsecurity.base.case1; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * @author <a href="mailto:me@tonglei.win">Tonglei</a> * @since 1.0 */ @SpringBootApplication public class Case1Application { public static void main(String[] args) { SpringApplication.run(Case1Application.class, args); } }
打開命令行,進入工程根目錄,執行編譯命令瀏覽器
gradle compileJava
執行運行命令安全
gradle run
訪問 http://localhost:8080/user/allbash
此時瀏覽器顯示以下app
用戶名填入 usermaven
密碼每次啓動時自動生成,能夠在日誌中找到spring-boot
...
2019-08-08 15:13:10.028 INFO 824 --- [ main] .s.s.UserDetailsServiceAutoConfiguration :
Using generated security password: 8c20d4a7-7507-41ce-a271-a75fbe0c7deegradle
認證經過後,可看到 User 控制器返回內容
最簡單的 spring-security 項目只須要在項目依賴中增長 spring-boot-starter-security 便可。
默認狀況下,該項目的全部資源地址均需認證成功後才能訪問。默認帳戶 user,密碼可從日誌中找到。
若是想取消默認的安全設置,須要在配置文件中增長如下內容:
security.basic.enabled = false # 默認禁用 spring-security 安全配置