分享

Spring认证指南:了解如何使用 Spring Security 保护您的 Web 应用程序

 王先生的内容 2022-03-07

原标题:Spring认证指南:了解如何使用 Spring Security 保护您的 Web 应用程序。(Spring中国教育管理中心)

保护 Web 应用程序

本指南将引导您完成使用受 Spring Security 保护的资源创建简单 Web 应用程序的过程。

你将建造什么

您将构建一个 Spring MVC 应用程序,该应用程序使用由固定用户列表支持的登录表单来保护页面。

你需要什么

  • 约15分钟

  • 最喜欢的文本编辑器或 IDE

  • JDK 1.8或更高版本

  • Gradle 4+或Maven 3.2+

  • 您还可以将代码直接导入 IDE:

    • 弹簧工具套件 (STS)

    • IntelliJ IDEA

如何完成本指南

像大多数 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 开始

您可以使用这个预先初始化的项目并单击 Generate 下载 ZIP 文件。此项目配置为适合本教程中的示例。

手动初始化项目:

  1. 导航到https://start.。该服务提取应用程序所需的所有依赖项,并为您完成大部分设置。

  2. 选择 Gradle 或 Maven 以及您要使用的语言。本指南假定您选择了 Java。

  3. 单击Dependencies并选择Spring WebThymeleaf

  4. 单击生成

  5. 下载生成的 ZIP 文件,该文件是根据您的选择配置的 Web 应用程序的存档。

如果您的 IDE 具有 Spring Initializr 集成,您可以从您的 IDE 完成此过程。

你也可以从 Github 上 fork 项目并在你的 IDE 或其他编辑器中打开它。

创建不安全的 Web 应用程序

在将安全性应用到 Web 应用程序之前,您需要一个 Web 应用程序来保护。本部分将引导您创建一个简单的 Web 应用程序。然后,您将在下一节中使用 Spring Security 对其进行保护。

Web 应用程序包括两个简单的视图:一个主页和一个“Hello, World”页面。主页在以下 Thymeleaf 模板中定义(来自
src/main/resources/templates/home.html
):

<!DOCTYPE html><html xmlns="http://www./1999/xhtml" xmlns:th="https://www." xmlns:sec="https://www./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./1999/xhtml" xmlns:th="https://www."
      xmlns:sec="https://www./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;@Configurationpublic 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,您需要在 in 的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.6.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./POM/4.0.0" xmlns:xsi="http://www./2001/XMLSchema-instance"
xsi:schemaLocation="http://maven./POM/4.0.0 https://maven./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.6.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>securing-web-complete</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>securing-web-complete</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@EnableWebSecuritypublic 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)方法定义了哪些 URL 路径应该被保护,哪些不应该。具体来说,//home路径被配置为不需要任何身份验证。所有其他路径都必须经过身份验证。

当用户成功登录时,他们将被重定向到先前请求的需要身份验证的页面。有一个自定义/login页面(由 指定loginPage()),每个人都可以查看。

userDetailsService()方法使用单个用户设置内存中的用户存储。该用户的用户名是user,密码是password,角色是USER

现在您需要创建登录页面。该视图已经有一个视图控制器login,因此您只需要创建登录视图本身,如以下清单(来自
src/main/resources/templates/login.html
)所示:

<!DOCTYPE html><html xmlns="http://www./1999/xhtml" xmlns:th="https://www."
      xmlns:sec="https://www./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./1999/xhtml" xmlns:th="https://www."
      xmlns:sec="https://www./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;@SpringBootApplicationpublic 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-securering-web-0.1.0.jar

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

java -jar 目标/gs-securering-web-0.1.0.jar

此处描述的步骤创建了一个可运行的 JAR。您还可以构建经典的 WAR 文件。

应用程序启动后,将浏览器指向http://localhost:8080. 您应该会看到主页,如下图所示:

应用程序的主页

当您单击该链接时,它会尝试将您带到位于 的问候语页面/hello。但是,由于该页面是安全的并且您还没有登录,它会将您带到登录页面,如下图所示:

登录页面

如果您使用不安全版本跳到此处,则看不到登录页面。您应该备份并编写其余基于安全性的代码。

在登录页面,分别输入用户名和密码字段,以测试用户身份user登录password。提交登录表单后,您将通过身份验证,然后进入欢迎页面,如下图所示:

安全的问候页面

如果您单击注销按钮,您的身份验证将被撤销,您将返回登录页面,并显示一条消息,表明您已注销。

概括

恭喜!您已经开发了一个使用 Spring Security 保护的简单 Web 应用程序。

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多