- Spring Boot 教程
- Spring Boot - 首頁
- Spring Boot - 簡介
- Spring Boot - 快速入門
- Spring Boot - 引導
- Spring Tool Suite
- Spring Boot - Tomcat 部署
- Spring Boot - 構建系統
- Spring Boot - 程式碼結構
- Spring Bean & 依賴注入
- Spring Boot - 執行器
- Spring Boot - 啟動器
- Spring Boot - 應用屬性
- Spring Boot - 配置
- Spring Boot - 註解
- Spring Boot - 日誌
- 構建 RESTful Web 服務
- Spring Boot - 異常處理
- Spring Boot - 攔截器
- Spring Boot - Servlet 過濾器
- Spring Boot - Tomcat 埠號
- Spring Boot - Rest 模板
- Spring Boot - 檔案處理
- Spring Boot - 服務元件
- Spring Boot - Thymeleaf
- 消費 RESTful Web 服務
- Spring Boot - CORS 支援
- Spring Boot - 國際化
- Spring Boot - 排程
- Spring Boot - 啟用 HTTPS
- Spring Boot - Eureka 伺服器
- 使用 Eureka 註冊服務
- 閘道器代理伺服器和路由
- Spring Cloud 配置伺服器
- Spring Cloud 配置客戶端
- Spring Boot - Actuator
- Spring Boot - Admin 伺服器
- Spring Boot - Admin 客戶端
- Spring Boot - 啟用 Swagger2
- Spring Boot - 使用 SpringDoc OpenAPI
- Spring Boot - 建立 Docker 映象
- 跟蹤微服務日誌
- Spring Boot - Flyway 資料庫
- Spring Boot - 傳送郵件
- Spring Boot - Hystrix
- Spring Boot - Web Socket
- Spring Boot - 批處理服務
- Spring Boot - Apache Kafka
- Spring Boot - Twilio
- Spring Boot - 單元測試用例
- Rest Controller 單元測試
- Spring Boot - 資料庫處理
- Web 應用安全
- Spring Boot - 帶 JWT 的 OAuth2
- Spring Boot - Google Cloud Platform
- Spring Boot - Google OAuth2 登入
- Spring Boot 資源
- Spring Boot - 快速指南
- Spring Boot - 有用資源
- Spring Boot - 討論
Spring Boot - Web 應用安全
如果在類路徑中添加了 Spring Boot Security 依賴項,則 Spring Boot 應用程式會自動為所有 HTTP 端點要求基本身份驗證。端點“/”和“/home”不需要任何身份驗證。所有其他端點都需要身份驗證。
要將 Spring Boot Security 新增到您的 Spring Boot 應用程式中,我們需要在構建配置檔案中新增 Spring Boot Starter Security 依賴項。
Maven 使用者可以在 pom.xml 檔案中新增以下依賴項。
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
Gradle 使用者可以在 build.gradle 檔案中新增以下依賴項。
compile("org.springframework.boot:spring-boot-starter-security")
保護 Web 應用程式
首先,使用 Thymeleaf 模板建立一個不安全的 Web 應用程式。
從 Spring Initializer 頁面 www.start.spring.io 下載 Spring Boot 專案,並選擇以下依賴項:
- Spring Web
- Spring Security
- Thymeleaf
然後,在 **src/main/resources/templates** 目錄下建立一個 home.html 檔案。
home.html
<!DOCTYPE html>
<html xmlns = "http://www.w3.org/1999/xhtml"
xmlns:th = "http://www.thymeleaf.org"
xmlns:sec = "http://www.thymeleaf.org/thymeleaf-extras-springsecurity6">
<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>
使用 Thymeleaf 模板在 HTML 檔案中定義簡單的檢視 ** /hello** 。
現在,在 **src/main/resources/templates** 目錄下建立一個 hello.html。
hello.html
<!DOCTYPE html>
<html xmlns = "http://www.w3.org/1999/xhtml"
xmlns:th = "http://www.thymeleaf.org"
xmlns:sec = "http://www.thymeleaf.org/thymeleaf-extras-springsecurity6">
<head>
<title>Hello World!</title>
</head>
<body>
<h1>Hello world!</h1>
</body>
</html>
現在,我們需要為 home 和 hello 檢視設定 Spring MVC - 檢視控制器。
為此,建立一個 ViewsController 類。
ViewsController.java
package com.tutorialspoint.websecurity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class ViewsController {
@GetMapping("/hello")
public String hello() {
return "hello";
}
@GetMapping("/home")
public String home() {
return "home";
}
@GetMapping("/")
public String index() {
return "hello";
}
@GetMapping("/login")
public String login() {
return "login";
}
}
現在,建立一個 Web 安全配置檔案,用於透過基本身份驗證保護應用程式以訪問 HTTP 端點。
WebSecurityConfig.java
package com.tutorialspoint.websecurity;
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.configurers.AbstractHttpConfigurer;
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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
public class WebSecurityConfig {
@Bean
protected UserDetailsService userDetailsService() {
UserDetails user = User.builder()
.username("user")
.password(passwordEncoder().encode("password"))
.roles("USER")
.build();
return new InMemoryUserDetailsManager(user);
}
@Bean
protected PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
protected SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(
request -> request
.requestMatchers("/").permitAll()
.requestMatchers("/home").permitAll()
.anyRequest().authenticated()
)
.formLogin(form -> form
.loginPage("/login")
.permitAll())
.logout(config -> config
.logoutSuccessUrl("/login"))
.build();
}
}
現在,在 **src/main/resources** 目錄下建立一個 login.html 檔案,以允許使用者透過登入螢幕訪問 HTTP 端點。
login.html
<!DOCTYPE html>
<html xmlns = "http://www.w3.org/1999/xhtml" xmlns:th = "http://www.thymeleaf.org"
xmlns:sec = "http://www.thymeleaf.org/thymeleaf-extras-springsecurity6">
<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>
最後,更新 hello.html 檔案 - 以允許使用者從應用程式登出並顯示當前使用者名稱,如下所示:
hello.html
<!DOCTYPE html>
<html xmlns = "http://www.w3.org/1999/xhtml" xmlns:th = "http://www.thymeleaf.org"
xmlns:sec = "http://www.thymeleaf.org/thymeleaf-extras-springsecurity6">
<head>
<title>Hello World!</title>
</head>
<body>
<h1 th:inline="text">Hello <span sec:authentication="name"></span>!</h1>
<form th:action = "@{/logout}" method = "post">
<input type = "submit" value = "Sign Out"/>
</form>
</body>
</html>
下面給出主 Spring Boot 應用程式的程式碼:
WebsecurityApplication.java
package com.tutorialspoint.websecurity;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class WebsecurityApplication {
public static void main(String[] args) {
SpringApplication.run(WebsecurityDemoApplication.class, args);
}
}
下面給出構建配置檔案的完整程式碼。
Maven - 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.3.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.tutorialspoint</groupId>
<artifactId>websecurity</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>websecurity</name>
<description>Demo project for Spring Boot</description>
<url/>
<licenses>
<license/>
</licenses>
<developers>
<developer/>
</developers>
<scm>
<connection/>
<developerConnection/>
<tag/>
<url/>
</scm>
<properties>
<java.version>21</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-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity6</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-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 - build.gradle
buildscript {
ext {
springBootVersion = '3.3.4'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
}
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
group = 'com.tutorialspoint'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 21
repositories {
mavenCentral()
}
dependencies {
compile('org.springframework.boot:spring-boot-starter-security')
compile('org.springframework.boot:spring-boot-starter-thymeleaf')
compile('org.springframework.boot:spring-boot-starter-web')
testCompile('org.springframework.boot:spring-boot-starter-test')
testCompile('org.springframework.security:spring-security-test')
}
編譯和執行
現在,建立一個可執行的 JAR 檔案,並使用以下 Maven 或 Gradle 命令執行 Spring Boot 應用程式。
Maven 使用者可以使用以下命令:
mvn clean install
“BUILD SUCCESS”後,您可以在 target 目錄下找到 JAR 檔案。
Gradle 使用者可以使用以下所示的命令:
gradle clean build
“BUILD SUCCESSFUL”後,您可以在 build/libs 目錄下找到 JAR 檔案。
現在,使用以下所示的命令執行 JAR 檔案:
java –jar <JARFILE>
在您的 Web 瀏覽器中訪問 URL **https://:8080/**。您可以看到如下所示的輸出。
登入頁面
點選登出按鈕
登入
使用使用者名稱/密碼登入並檢視主頁。
已登出
點選登出按鈕。
無效的使用者名稱密碼
嘗試使用無效的使用者名稱/密碼登入。