最近一段時間學習了 Spring Security,併成功整合到了項目中(基於Sping-boot2.x)。在此準備將踩坑過程記錄一下,順便講述下如何一步一步應用到項目中的。java
<?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"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.1.7.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>demo</artifactId> <version>0.0.1-SNAPSHOT</version> <name>demo</name> <properties> <java.version>1.8</java.version> </properties> <dependencies> <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> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
package com.example.demo.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class IndexController { @GetMapping("/hello") public Object sayHello(){ return "hello world"; } }
項目啓動成功後, 用瀏覽器訪問 http://localhost:8080/hello 正常狀況下瀏覽器會打印出來 "hello world" 字符串。可是咱們由於咱們引入了 Spring Security 依賴。瀏覽器會自動跳轉到 http://localhost:8080/login 。以下圖:github
用戶名默認是 user,源碼中能夠查到。密碼在項目啓動時已經在控制檯打印出來了。
web
輸入用戶名和密碼spring