# 保護Web應用程序
本指南將引導您完成使用受Spring Security保護的資源創建簡單的Web應用程序的過程。
## 你會建立什么
您將構建一個Spring MVC應用程序,該應用程序使用由固定用戶列表支持的登錄表單來保護頁面的安全。
## 你需要什么
* 約15分鐘
* 最喜歡的文本編輯器或IDE
* [JDK 1.8](http://www.oracle.com/technetwork/java/javase/downloads/index.html) 或更高版本
* [Gradle 4+](http://www.gradle.org/downloads) 或 [Maven 3.2+](https://maven.apache.org/download.cgi)
* 您還可以將代碼直接導入到IDE中:
* [彈簧工具套件(STS)](https://spring.io/guides/gs/sts)
* [IntelliJ IDEA](https://spring.io/guides/gs/intellij-idea/)
## 如何完成本指南
像大多數Spring 一樣 [入門指南](https://spring.io/guides) ,您可以從頭開始并完成每個步驟,也可以繞過您已經熟悉的基本設置步驟。 無論哪種方式,您最終都可以使用代碼。
要 **從頭開始** ,請繼續進行“ [從Spring Initializr開始”](https://spring.io/guides/gs/securing-web/#scratch) 。
要 **跳過基礎知識** ,請執行以下操作:
* [下載](https://github.com/spring-guides/gs-securing-web/archive/master.zip) 并解壓縮本指南的源存儲庫,或使用 對其進行克隆 [Git](https://spring.io/understanding/Git) : `git clone [https://github.com/spring-guides/gs-securing-web.git](https://github.com/spring-guides/gs-securing-web.git)`
* 光盤進入 `gs-securing-web/initial`
* 繼續 [創建一個不安全的Web應用程序](https://spring.io/guides/gs/securing-web/#initial) 。
**完成后** ,您可以根據中的代碼檢查結果 `gs-securing-web/complete`.
## 從Spring Initializr開始
如果您使用Maven,請訪問 [Spring Initializr](https://start.spring.io/#!type=maven-project&language=java&platformVersion=2.4.3.RELEASE&packaging=jar&jvmVersion=1.8&groupId=com.example&artifactId=securing-web&name=securing-web&description=Demo%20project%20for%20Spring%20Boot&packageName=com.example.securing-web&dependencies=web,thymeleaf) 以生成具有所需依賴項(Spring Web和Thymeleaf)的新項目。
以下清單顯示了 `pom.xml` 選擇Maven時創建的文件:
~~~
<?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>2.4.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>securing-web</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>securing-web</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</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>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
~~~
如果您使用Gradle,請訪問 [Spring Initializr](https://start.spring.io/#!type=gradle-project&language=java&platformVersion=2.4.3.RELEASE&packaging=jar&jvmVersion=1.8&groupId=com.example&artifactId=securing-web&name=securing-web&description=Demo%20project%20for%20Spring%20Boot&packageName=com.example.securing-web&dependencies=web,thymeleaf) 以生成具有所需依賴項(Spring Web和Thymeleaf)的新項目。
以下清單顯示了 `build.gradle` 選擇Gradle時創建的文件:
~~~
plugins {
id 'org.springframework.boot' version '2.4.3'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-starter-web'
testImplementation('org.springframework.boot:spring-boot-starter-test')
}
test {
useJUnitPlatform()
}
~~~
### 手動初始化(可選)
如果要手動初始化項目而不是使用前面顯示的鏈接,請按照以下步驟操作:
1. 導航到 [https://start.spring.io](https://start.spring.io) 。 該服務提取應用程序所需的所有依賴關系,并為您完成大部分設置。
2. 選擇Gradle或Maven以及您要使用的語言。 本指南假定您選擇了Java。
3. 單擊 **Dependencies,** 然后選擇 **Spring Web** 和 **Thymeleaf** 。
4. 點擊 **生成** 。
5. 下載生成的ZIP文件,該文件是使用您的選擇配置的Web應用程序的存檔。
如果您的IDE集成了Spring Initializr,則可以從IDE中完成此過程。
## 創建一個不安全的Web應用程序
在將安全性應用于Web應用程序之前,需要Web應用程序進行安全保護。 本節將引導您創建一個簡單的Web應用程序。 然后,您將在下一部分中使用Spring Security對其進行保護。
該Web應用程序包括兩個簡單的視圖:主頁和“ Hello,World”頁面。 主頁在以下Thymeleaf模板中定義(來自 `src/main/resources/templates/home.html`):
~~~
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org" xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Spring Security Example</title>
</head>
<body>
<h1>Welcome!</h1>
<p>Click <a th:href="@{/hello}">here</a> to see a greeting.</p>
</body>
</html>
~~~
這個簡單的視圖包含一個指向 `/hello` 頁面,該頁面在以下Thymeleaf模板中定義(來自 `src/main/resources/templates/hello.html`):
~~~
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org"
xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Hello World!</title>
</head>
<body>
<h1>Hello world!</h1>
</body>
</html>
~~~
該Web應用程序基于Spring MVC。 因此,您需要配置Spring MVC并設置視圖控制器以公開這些模板。 以下清單(來自 `src/main/java/com/example/securingweb/MvcConfig.java`)顯示了一個在應用程序中配置Spring MVC的類:
~~~
package com.example.securingweb;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class MvcConfig implements WebMvcConfigurer {
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/home").setViewName("home");
registry.addViewController("/").setViewName("home");
registry.addViewController("/hello").setViewName("hello");
registry.addViewController("/login").setViewName("login");
}
}
~~~
這 `addViewControllers()` 方法(該方法將覆蓋其中相同名稱的方法 `WebMvcConfigurer`)添加了四個視圖控制器。 兩個視圖控制器引用名稱為 `home` (在 `home.html`),另一個引用了名為的視圖 `hello` (在 `hello.html`)。 第四個視圖控制器引用另一個名為 `login`。 您將在下一部分中創建該視圖。
此時,您可以跳至“ [Run the Application](https://spring.io/guides/gs/securing-web/#run_the_app) ”并運行應用程序,而無需登錄任何內容。
既然您擁有一個不安全的Web應用程序,則可以為其添加安全性。
## 設置Spring Security
假設您要防止未經授權的用戶查看位于的問候頁面 `/hello`。 現在,如果訪問者單擊主頁上的鏈接,他們將看到問候,沒有任何障礙可以阻止他們。 您需要添加一個屏障,以迫使訪問者登錄才能看到該頁面。
您可以通過在應用程序中配置Spring Security來實現。 如果Spring Security在類路徑中,則Spring Boot會 [自動保護所有HTTP端點](https://docs.spring.io/spring-boot/docs/2.4.3/reference/htmlsingle/#boot-features-security) 使用“基本”身份驗證 。 但是,您可以進一步自定義安全設置。 您需要做的第一件事是將Spring Security添加到類路徑中。
使用Gradle,您需要在代碼行中添加兩行(一行用于應用程序,另一行用于測試)。 `dependencies` 封閉在 `build.gradle`,如以下清單所示:
~~~
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.security:spring-security-test'
~~~
以下清單顯示了成品 `build.gradle` 文件:
~~~
plugins {
id 'org.springframework.boot' version '2.4.3'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
}
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.security:spring-security-test'
testImplementation('org.springframework.boot:spring-boot-starter-test')
}
test {
useJUnitPlatform()
}
~~~
使用Maven,您需要將兩個額外的條目(一個用于應用程序,一個用于測試)添加到 `<dependencies>` 元素在 `pom.xml`,如以下清單所示:
~~~
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
~~~
以下清單顯示了成品 `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>2.4.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>securing-web</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>securing-web</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</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-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
~~~
以下安全配置(來自 `src/main/java/com/example/securingweb/WebSecurityConfig.java`)確保只有經過身份驗證的用戶才能看到秘密問候:
~~~
package com.example.securingweb;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
@Bean
@Override
public UserDetailsService userDetailsService() {
UserDetails user =
User.withDefaultPasswordEncoder()
.username("user")
.password("password")
.roles("USER")
.build();
return new InMemoryUserDetailsManager(user);
}
}
~~~
這 `WebSecurityConfig` 該類帶有注釋 `@EnableWebSecurity`啟用S??pring Security的Web安全支持并提供Spring MVC集成。 它也延伸 `WebSecurityConfigurerAdapter` 并覆蓋了它的幾種方法來設置網絡安全配置的某些細節。
這 `configure(HttpSecurity)`方法定義應該保護哪些URL路徑,哪些不應該保護。 具體來說, `/` 和 `/home`路徑配置為不需要任何身份驗證。 所有其他路徑必須經過驗證。
用戶成功登錄后,他們將被重定向到先前要求的頁面,該頁面需要身份驗證。 有一個習慣 `/login` 頁面(由 `loginPage()`),每個人都可以查看。
這 `userDetailsService()`方法用一個用戶建立一個內存用戶存儲。 該用戶的用戶名為 `user`,密碼為 `password`,以及 `USER`.
現在,您需要創建登錄頁面。 已經有一個視圖控制器 `login` 視圖,因此您只需要創建登錄視圖本身,如下面的清單(來自 `src/main/resources/templates/login.html`)顯示:
~~~
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org"
xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Spring Security Example </title>
</head>
<body>
<div th:if="${param.error}">
Invalid username and password.
</div>
<div th:if="${param.logout}">
You have been logged out.
</div>
<form th:action="@{/login}" method="post">
<div><label> User Name : <input type="text" name="username"/> </label></div>
<div><label> Password: <input type="password" name="password"/> </label></div>
<div><input type="submit" value="Sign In"/></div>
</form>
</body>
</html>
~~~
此Thymeleaf模板提供了一種表單,可捕獲用戶名和密碼并將其發布到 `/login`。 根據配置,Spring Security提供了一個過濾器,該過濾器攔截該請求并驗證用戶身份。 如果用戶認證失敗,則頁面被重定向到 `/login?error`,然后頁面會顯示相應的錯誤消息。 成功注銷后,您的申請將發送到 `/login?logout`,然后頁面會顯示相應的成功消息。
最后,您需要為訪問者提供一種顯示當前用戶名并注銷的方法。 為此,請更新 `hello.html` 向當前用戶問好并包含一個 `Sign Out`形式,如下清單(來自 `src/main/resources/templates/hello.html`)顯示:
~~~
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="https://www.thymeleaf.org"
xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title>Hello World!</title>
</head>
<body>
<h1 th:inline="text">Hello [[${#httpServletRequest.remoteUser}]]!</h1>
<form th:action="@{/logout}" method="post">
<input type="submit" value="Sign Out"/>
</form>
</body>
</html>
~~~
我們通過使用Spring Security的集成來顯示用戶名 `HttpServletRequest#getRemoteUser()`。 “登出”表單將POST提交到 `/logout`。 成功注銷后,它將用戶重定向到 `/login?logout`.
## 運行應用程序
Spring Initializr為您創建一個應用程序類。 在這種情況下,您無需修改??類。 以下清單(來自 `src/main/java/com/example/securingweb/SecuringWebApplication.java`)顯示了應用程序類:
~~~
package com.example.securingweb;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SecuringWebApplication {
public static void main(String[] args) throws Throwable {
SpringApplication.run(SecuringWebApplication.class, args);
}
}
~~~
### 建立可執行的JAR
您可以使用Gradle或Maven從命令行運行該應用程序。 您還可以構建一個包含所有必需的依賴項,類和資源的可執行JAR文件,然后運行該文件。 生成可執行jar使得在整個開發生命周期中,跨不同環境等等的情況下,都可以輕松地將服務作為應用程序進行發布,版本控制和部署。
如果您使用Gradle,則可以通過使用以下命令運行該應用程序 `./gradlew bootRun`。 或者,您可以通過使用以下命令構建JAR文件: `./gradlew build` 然后運行JAR文件,如下所示:
~~~
java -jar build/libs/gs-securing-web-0.1.0.jar
~~~
如果您使用Maven,則可以通過使用以下命令運行該應用程序 `./mvnw spring-boot:run`。 或者,您可以使用以下命令構建JAR文件: `./mvnw clean package` 然后運行JAR文件,如下所示:
~~~
java -jar target/gs-securing-web-0.1.0.jar
~~~
此處描述的步驟將創建可運行的JAR。 您還可以 構建經典的WAR文件 。
應用程序啟動后,將瀏覽器指向 `[http://localhost:8080](http://localhost:8080)`。 您應該看到主頁,如下圖所示:

當您單擊鏈接時,它會嘗試將您帶到以下位置的問候頁面 `/hello`。 但是,由于該頁面是安全的,并且您尚未登錄,因此將您帶到登錄頁面,如下圖所示:

如果您使用不安全的版本跳到此處,則看不到登錄頁面。 您應該備份并編寫其余基于安全性的代碼。
在登錄頁面上,輸入以下內容以測試用戶身份登錄 `user` 和 `password`分別用于用戶名和密碼字段。 提交登錄表單后,將對您進行身份驗證,然后轉到問候頁面,如下圖所示:

如果單擊“ **退出”** 按鈕,則您的身份驗證將被撤消,并且將返回到登錄頁面,并顯示一條消息,指示您已注銷。
## 概括
恭喜你! 您已經開發了一個受Spring Security保護的簡單Web應用程序。
- springboot概述
- springboot構建restful服務
- spring構建一個RESTful Web服務
- spring定時任務
- 消費RESTful Web服務
- gradle構建項目
- maven構建項目
- springboot使用jdbc
- springboot應用上傳文件
- 使用LDNA驗證用戶
- 使用 spring data redis
- 使用 spring RabbitTemplate消息隊列
- 用no4j訪問nosql數據庫
- springboot驗證web表單
- Spring Boot Actuator構j建服務
- 使用jms傳遞消息
- springboot創建批處理服務
- spring security保護web 安全
- 在Pivotal GemFire中訪問數據
- 使用Spring Integration
- 使用springboot jpa進行數據庫操作
- 數據庫事務操作
- 操作mongodb
- springmvc+tymleaf創建web應用
- 將Spring Boot JAR應用程序轉換為WAR
- 創建異步服務
- spring提交表單
- 使用WebSocket構建交互式Web應用程序
- 使用REST訪問Neo4j數據
- jquery消費restful
- springboot跨域請求
- 消費SOAP Web服務
- springboot使用緩存
- 使用Vaadin創建CRUD UI
- 使用REST訪問JPA數據
- 使用REST訪問Pivotal GemFire中的數據
- 構建soap服務
- 使用rest訪問mongodb數據
- 構建springboot應用docker鏡像
- 從STS部署到Cloud Foundry
- springboot測試web應用
- springboot訪問mysql
- springboot編寫自定義模塊并使用
- 使用Google Cloud Pub / Sub進行消息傳遞
- 構建反應式RESTful Web服務
- 使用Redis主動訪問數據
- Spring Boot 部署到Kubernetes
- 使用反應式協議R2DBC訪問數據
- Spring Security架構
- spring構建Docker鏡像詳解
- Spring Boot和OAuth2
- springboot應用部署到k8s
- spring構建rest服務詳解