SpringBoot 2 Web 应用加固

开篇词

该指南将引导你完成使用受 Spring Security 保护的资源创建简单的 Web 应用。
 

你将创建的应用

我们将构建一个 Spring MVC 应用,该应用使用由固定用户列表来支撑的登录表单来保护页面的安全。
 

你将需要的工具

如何完成这个指南

像大多数的 Spring 入门指南一样,你可以从头开始并完成每个步骤,也可以绕过你已经熟悉的基本设置步骤。如论哪种方式,你最终都有可以工作的代码。

  • 要从头开始,移步至从 Spring Initializr 开始
  • 要跳过基础,执行以下操作:
    • 下载并解压缩该指南将用到的源代码,或借助 Git 来对其进行克隆操作:git clone https://github.com/spring-guides/gs-securing-web.git
    • 切换至 gs-securing-web/initial 目录;
    • 跳转至该指南的创建一个不安全的 Web 应用

待一切就绪后,可以检查一下 gs-securing-web/complete 目录中的代码。

从 Spring Initializr 开始

对于所有的 Spring 应用来说,你应该从 Spring Initializr 开始。Initializr 提供了一种快速的方法来提取应用程序所需的依赖,并为你完成许多设置。该示例需要 Spring Web 和 Thymeleaf 依赖。下图显示了此示例项目的 Initializr 设置:
Spring Initializr 界面

上图显示了选择 Maven 作为构建工具的 Initializr。你也可以使用 Gradle。它还将 com.examplesecuring-web 的值分别显示为 Group 和 Artifact。在本示例的其余部分,将用到这些值。

以下清单显示了选择 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>2.2.2.RELEASE</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>
			<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>

以下清单显示了在选择 Gradle 时创建的 build.gradle 文件:

plugins {
	id 'org.springframework.boot' version '2.2.2.RELEASE'
	id 'io.spring.dependency-management' version '1.0.8.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') {
		exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
	}
}

test {
	useJUnitPlatform()
}

创建一个不安全的 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 的视图。我们将在下一部分中创建该视图。

此时,我们可以跳转至 “运行应用”,而无需输入任何内容。

既然我们拥有不安全的 Web 应用,则可以为其添加安全性。
 

搭建 Spring Security

假设我们要防止未经授权的用户查看 /hello 的问候页面。现在,如果访问者点击主页上的链接,他们会看到问候,没有障碍可以阻止他们。我们需要添加一个屏障,以迫使访问者登录之后才能看到该页面。

我们可以通过在应用中配置 Spring Security 来实现。如果 Spring Security 在类路径上,Spring Boot 会使用 “基本” 身份验证自动保护所有 HTTP 端点。但是,我们可以进一步自定义安全配置。我们需要做的第一件事是将 Spring Security 添加到类路径中。

使用 Gradle,我们需要在 build.gradledependencies 闭包中添加两行(对于应用来说是一行),如下清单所示:

implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.security:spring-security-test'

以下清单显示了完整的 build.gradle 文件:

plugins {
	id 'org.springframework.boot' version '2.2.2.RELEASE'
	id 'io.spring.dependency-management' version '1.0.8.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') {
		exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
	}
}

test {
	useJUnitPlatform()
}

使用 Maven,我们需要向 pom.xml 中的 <dependencies> 元素添加两个额外的条目(一个用于应用,一个用于测试),如下清单所示:

<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.2.2.RELEASE</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>
			<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>

以下安全配置(来自 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 注解,以启用 Spring Security 的 Web 安全支持并提供 Spring MVC 集成。它还扩展了 WebSecurityConfigurerAdapter 并覆盖了其一些方法来设置 Web 安全配置的某些细节。

configure(HttpSecurity) 方法定义保护哪些地址路径,不应该保护哪些地址路径。具体来说,将 //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 来运行应用。或通过借助 ./gradlew build 来构建 JAR 文件,然后运行 JAR 文件,如下所示:

java -jar build/libs/gs-securing-web-0.1.0.jar

由官网提供的以上这条命令的执行结果与我本地的不一样,我需要这样才能运行:java -jar build/libs/securing-web-0.0.1-SNAPSHOT.jar

如果使用 Maven,则可以借助 ./mvnw spring-boot:run 来运行该用。或可以借助 ./mvnw clean package 来构建 JAR 文件,然后运行 JAR 文件,如下所示:

java -jar target/gs-securing-web-0.1.0.jar

由官网提供的以上这条命令的执行结果与我本地的不一样,我需要这样才能运行:java -jar target/securing-web-0.0.1-SNAPSHOT.jar

我们还可以构建一个经典的 WAR 文件

应用启动后,访问 http://localhost:8080。我们应该看到主页,如下图所示:
主页
当我们单击链接时,它会尝试将我们带往 /hello 的问候页面。但是,由于该页面受到登录保护,而我们尚未登录,因此它将带我们前往登录页面,如下图所示:
登录页面

如果我们在此处跳到未受保护的版本,则看不到登录页面。我们应该备份之后再进行基于受保护版本代码的编写。

在登录页面上,通过分别在用户名和密码字段中输入 userpassword,以测试用户身份登录。提交登录表单后,将对我们进行身份验证,然后被转至问候页面,如下图所示:
问候页面
如果单击 Sign Out 按钮,则我们的身份验证将被撤销,将我们返回至登录页面并显示一条消息,以指示我们已注销。
 

概述

恭喜你!我们已经开发了一个受 Spring Security 保护的简单 Web 应用。
 

参见

以下指南也可能会有所帮助:

想看指南的其他内容?请访问该指南的所属专栏:《Spring 官方指南

发布了132 篇原创文章 · 获赞 6 · 访问量 7965

猜你喜欢

转载自blog.csdn.net/stevenchen1989/article/details/104152221