Spring Boot 与 Docker
观察 GraphQL 的实际运行

本指南将引导您完成创建应用程序并使用 Spring Security LDAP 模块对其进行安全保护的过程。

您将构建的内容 {#_what_you_will_build}

您将构建一个由 Spring Security 内置的基于 Java 的 LDAP 服务器保护的简单 Web 应用程序。您将使用包含一组用户的数据文件来加载 LDAP 服务器。

所需准备

如何完成本指南

与大多数 Spring 入门指南 一样,您可以从头开始并完成每个步骤,也可以跳过您已经熟悉的基本设置步骤。无论哪种方式,您最终都会获得可运行的代码。

从头开始,请继续 使用 Spring Initializr

跳过基础知识,请执行以下操作:

完成后,您可以对照 gs-authenticating-ldap/complete 中的代码检查您的结果。

从 Spring Initializr 开始

因为本指南的目的是为不安全的 Web 应用程序添加安全保护,所以您将首先构建一个不安全的 Web 应用程序,然后在指南的后续部分中,再添加 Spring Security 和 LDAP 功能的更多依赖项。

您可以使用这个预初始化项目,点击生成以下载一个 ZIP 文件。该项目已配置为适用于本教程中的示例。

要手动初始化项目:

  1. 访问 https://start.spring.io。该服务会为您拉取应用程序所需的所有依赖项,并完成大部分设置工作。

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

  3. 点击 Dependencies 并选择 Spring Web

  4. 点击 Generate

  5. 下载生成的 ZIP 文件,这是一个根据您的选择配置好的 Web 应用程序的压缩包。

如果您的 IDE 集成了 Spring Initializr,您可以直接在 IDE 中完成此过程。

您还可以从 Github 上 fork 该项目,并在您的 IDE 或其他编辑器中打开它。

创建一个简单的Web控制器

在 Spring 中,REST 端点是 Spring MVC 控制器。以下 Spring MVC 控制器(来自 src/main/java/com/example/authenticatingldap/HomeController.java)通过返回一条简单的消息来处理 GET / 请求:

package com.example.authenticatingldap;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HomeController {

  @GetMapping("/")
  public String index() {
    return "Welcome to the home page!";
  }

}

整个类被标记为@RestController,这样Spring MVC可以自动检测到控制器(通过使用其内置的扫描功能)并自动配置必要的Web路由。

@RestController还告诉Spring MVC将文本直接写入HTTP响应体,因为没有视图。相反,当您访问该页面时,您会在浏览器中看到一个简单的消息(因为本指南的重点是使用LDAP保护页面)。

构建未加密的 Web 应用程序

在保护 Web 应用程序之前,您应该验证它是否正常工作。为此,您需要定义一些关键 bean,这可以通过创建一个 Application 类来实现。以下代码(来自 src/main/java/com/example/authenticatingldap/AuthenticatingLdapApplication.java)展示了该类:

package com.example.authenticatingldap;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class AuthenticatingLdapApplication {

  public static void main(String[] args) {
    SpringApplication.run(AuthenticatingLdapApplication.class, args);
  }

}

@SpringBootApplication 是一个便捷的注解,它添加了以下所有内容:

  • @Configuration: 将类标记为应用上下文的 bean 定义来源。

  • @EnableAutoConfiguration: 告诉 Spring Boot 根据类路径设置、其他 bean 和各种属性设置开始添加 bean。例如,如果 spring-webmvc 在类路径上,此注解会将应用程序标记为 Web 应用程序,并激活关键行为,例如设置 DispatcherServlet

  • @ComponentScan: 告诉 Spring 在 com/example 包中查找其他组件、配置和服务,使其能够找到控制器。

main() 方法使用 Spring Boot 的 SpringApplication.run() 方法来启动应用程序。您是否注意到没有一行 XML 代码?也没有 web.xml 文件。这个 Web 应用程序是 100% 纯 Java 的,您无需处理任何配置管道或基础设施的问题。

构建可执行的 JAR

您可以使用 Gradle 或 Maven 从命令行运行应用程序。您还可以构建一个包含所有必要依赖项、类和资源的可执行 JAR 文件并运行它。构建可执行的 JAR 文件使得在整个开发生命周期、跨不同环境等场景中,将服务作为应用程序进行交付、版本控制和部署变得非常容易。

如果您使用 Gradle,可以通过 ./gradlew bootRun 来运行应用程序。或者,您可以使用 ./gradlew build 构建 JAR 文件,然后运行该 JAR 文件,如下所示:

java -jar build/libs/gs-authenticating-ldap-0.1.0.jar

如果您使用 Maven,可以通过 ./mvnw spring-boot:run 来运行应用程序。或者,您可以使用 ./mvnw clean package 来构建 JAR 文件,然后按以下方式运行该 JAR 文件:

java -jar target/gs-authenticating-ldap-0.1.0.jar

这里描述的步骤创建了一个可运行的 JAR 文件。您也可以构建一个传统的 WAR 文件

如果您打开浏览器并访问 http://localhost:8080,您应该会看到以下纯文本:

Welcome to the home page!

配置 Spring Security

要配置 Spring Security,您首先需要在构建中添加一些额外的依赖项。

对于基于 Gradle 的构建,请将以下依赖项添加到 build.gradle 文件中:

implementation("org.springframework.boot:spring-boot-starter-security")
implementation("org.springframework.ldap:spring-ldap-core")
implementation("org.springframework.security:spring-security-ldap")
implementation("com.unboundid:unboundid-ldapsdk")

由于Gradle的依赖解析问题,必须引入 spring-tx。否则,Gradle会获取一个不兼容的旧版本。

对于基于 Maven 的构建,请将以下依赖项添加到 pom.xml 文件中:

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
        <groupId>org.springframework.ldap</groupId>
        <artifactId>spring-ldap-core</artifactId>
</dependency>
<dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-ldap</artifactId>
</dependency>
<dependency>
        <groupId>com.unboundid</groupId>
        <artifactId>unboundid-ldapsdk</artifactId>
</dependency>

这些依赖项添加了 Spring Security 和 UnboundId,一个开源的 LDAP 服务器。有了这些依赖项后,您就可以使用纯 Java 来配置您的安全策略,如下面的示例(来自 src/main/java/com/example/authenticatingldap/WebSecurityConfig.java)所示:

package com.example.authenticatingldap;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.Customizer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.context.annotation.Bean;
import org.springframework.beans.factory.annotation.Autowired;


@Configuration
public class WebSecurityConfig {

  @Bean
  public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
      .authorizeHttpRequests((authorize) -> authorize
        .anyRequest().fullyAuthenticated()
      )
      .formLogin(Customizer.withDefaults());

    return http.build();
  }

  @Autowired
  public void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth
      .ldapAuthentication()
        .userDnPatterns("uid={0},ou=people")
        .groupSearchBase("ou=groups")
        .contextSource()
          .url("ldap://localhost:8389/dc=springframework,dc=org")
          .and()
        .passwordCompare()
          .passwordEncoder(new BCryptPasswordEncoder())
          .passwordAttribute("userPassword");
  }

}

//@Configuration
//public class WebSecurityConfig {

//  @Bean
//  public SecurityFilterChain configure(HttpSecurity http) throws Exception {
//    return http
//      .authorizeRequests()
//      .anyRequest().authenticated()
//      .and()
//      .formLogin(Customizer.withDefaults())
//      .build();
//  }
//}

您还需要一个 LDAP 服务器。Spring Boot 提供了一个用纯 Java 编写的嵌入式服务器的自动配置,本指南中使用了该服务器。ldapAuthentication() 方法会进行配置,使得登录表单中的用户名被插入到 {0} 中,以便在 LDAP 服务器中搜索 uid={0},ou=people,dc=springframework,dc=org。此外,passwordCompare() 方法会配置编码器和密码属性的名称。

添加应用程序属性

Spring LDAP 要求在 application.properties 文件中设置三个应用程序属性:

spring.ldap.embedded.ldif=classpath:test-server.ldif
spring.ldap.embedded.base-dn=dc=springframework,dc=org
spring.ldap.embedded.port=8389

设置用户数据

LDAP 服务器可以使用 LDIF(LDAP 数据交换格式)文件来交换用户数据。application.properties 中的 spring.ldap.embedded.ldif 属性允许 Spring Boot 引入一个 LDIF 数据文件。这样可以轻松预加载演示数据。以下清单(来自 src/main/resources/test-server.ldif)展示了一个适用于此示例的 LDIF 文件:

dn: dc=springframework,dc=org
objectclass: top
objectclass: domain
objectclass: extensibleObject
dc: springframework

dn: ou=groups,dc=springframework,dc=org
objectclass: top
objectclass: organizationalUnit
ou: groups

dn: ou=subgroups,ou=groups,dc=springframework,dc=org
objectclass: top
objectclass: organizationalUnit
ou: subgroups

dn: ou=people,dc=springframework,dc=org
objectclass: top
objectclass: organizationalUnit
ou: people

dn: ou=space cadets,dc=springframework,dc=org
objectclass: top
objectclass: organizationalUnit
ou: space cadets

dn: ou=\"quoted people\",dc=springframework,dc=org
objectclass: top
objectclass: organizationalUnit
ou: "quoted people"

dn: ou=otherpeople,dc=springframework,dc=org
objectclass: top
objectclass: organizationalUnit
ou: otherpeople

dn: uid=ben,ou=people,dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: Ben Alex
sn: Alex
uid: ben
userPassword: $2a$10$c6bSeWPhg06xB1lvmaWNNe4NROmZiSpYhlocU/98HNr2MhIOiSt36

dn: uid=bob,ou=people,dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: Bob Hamilton
sn: Hamilton
uid: bob
userPassword: bobspassword

dn: uid=joe,ou=otherpeople,dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: Joe Smeth
sn: Smeth
uid: joe
userPassword: joespassword

dn: cn=mouse\, jerry,ou=people,dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: Mouse, Jerry
sn: Mouse
uid: jerry
userPassword: jerryspassword

dn: cn=slash/guy,ou=people,dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: slash/guy
sn: Slash
uid: slashguy
userPassword: slashguyspassword

dn: cn=quote\"guy,ou=\"quoted people\",dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: quote\"guy
sn: Quote
uid: quoteguy
userPassword: quoteguyspassword

dn: uid=space cadet,ou=space cadets,dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: Space Cadet
sn: Cadet
uid: space cadet
userPassword: spacecadetspassword



dn: cn=developers,ou=groups,dc=springframework,dc=org
objectclass: top
objectclass: groupOfUniqueNames
cn: developers
ou: developer
uniqueMember: uid=ben,ou=people,dc=springframework,dc=org
uniqueMember: uid=bob,ou=people,dc=springframework,dc=org

dn: cn=managers,ou=groups,dc=springframework,dc=org
objectclass: top
objectclass: groupOfUniqueNames
cn: managers
ou: manager
uniqueMember: uid=ben,ou=people,dc=springframework,dc=org
uniqueMember: cn=mouse\, jerry,ou=people,dc=springframework,dc=org

dn: cn=submanagers,ou=subgroups,ou=groups,dc=springframework,dc=org
objectclass: top
objectclass: groupOfUniqueNames
cn: submanagers
ou: submanager
uniqueMember: uid=ben,ou=people,dc=springframework,dc=org

使用 LDIF 文件并不是生产系统的标准配置。然而,它对于测试或教程的目的非常有用。

如果您访问 http://localhost:8080,您应该会被重定向到由 Spring Security 提供的登录页面。

输入用户名 ben 和密码 benspassword。您应该在浏览器中看到以下消息:

Welcome to the home page!

总结

恭喜!您已经编写了一个Web应用程序,并使用Spring Security对其进行了安全保护。在这种情况下,您使用了一个基于LDAP的用户存储

另请参阅

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

本页目录