Spring认证指南:了解如何使用 LDAP 保护应用程序

简介: Spring认证指南:了解如何使用 LDAP 保护应用程序

原标题:Spring认证中国教育管理中心-了解如何使用 LDAP 保护应用程序(Spring中国教育管理中心)

本指南将引导您完成创建应用程序并使用Spring Security LDAP 模块保护它的过程。

你将建造什么

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

你需要什么

  • 约15分钟
  • 最喜欢的文本编辑器或 IDE
  • JDK 1.8或更高版本
  • Gradle 4+或Maven 3.2+
  • 您还可以将代码直接导入 IDE:弹簧工具套件 (STS)IntelliJ IDEA

如何完成本指南

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

从头开始,请继续从 Spring Initializr 开始。

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

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

从 Spring Initializr 开始

因为本指南的重点是保护不安全的 Web 应用程序,您将首先构建一个不安全的 Web 应用程序,然后在本指南的后面,为 Spring Security 和 LDAP 功能添加更多依赖项。

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

手动初始化项目:

  1. 导航到https://start.spring.io。该服务提取应用程序所需的所有依赖项,并为您完成大部分设置。
  2. 选择 Gradle 或 Maven 以及您要使用的语言。本指南假定您选择了 Java。
  3. 单击Dependencies并选择Spring Web
  4. 单击生成
  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. 或者,您可以使用构建 JAR 文件./gradlew build,然后运行 JAR 文件,如下所示:

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

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

java -jar 目标/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.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
      .authorizeRequests()
        .anyRequest().fullyAuthenticated()
        .and()
      .formLogin();
  }
  @Override
  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");
  }
}

要自定义安全设置,请使用WebSecurityConfigurer. 在上面的示例中,这是通过覆盖
WebSecurityConfigurerAdapter
实现WebSecurityConfigurer接口的方法来完成的。

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

设置用户数据

LDAP 服务器可以使用 LDIF(LDAP 数据交换格式)文件来交换用户数据。里面的spring.ldap.embedded.ldif属性application.properties让 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 的用户存储。

相关文章
|
2月前
|
监控 Java 数据处理
【Spring云原生】Spring Batch:海量数据高并发任务处理!数据处理纵享新丝滑!事务管理机制+并行处理+实例应用讲解
【Spring云原生】Spring Batch:海量数据高并发任务处理!数据处理纵享新丝滑!事务管理机制+并行处理+实例应用讲解
|
2月前
|
安全 Java 数据安全/隐私保护
【深入浅出Spring原理及实战】「EL表达式开发系列」深入解析SpringEL表达式理论详解与实际应用
【深入浅出Spring原理及实战】「EL表达式开发系列」深入解析SpringEL表达式理论详解与实际应用
67 1
|
22天前
|
安全 数据安全/隐私保护
Springboot+Spring security +jwt认证+动态授权
Springboot+Spring security +jwt认证+动态授权
|
21天前
|
前端开发 Java 数据库连接
Spring系列文章1:Spring入门程序
Spring系列文章1:Spring入门程序
|
2天前
|
Java 开发者 UED
Spring Boot异常处理:优雅处理应用程序错误
【4月更文挑战第28天】异常处理是任何应用程序开发中不可或缺的一部分。Spring Boot提供了强大的异常处理机制,能够帮助开发者优雅地处理各种错误情况,并向用户提供友好的错误信息。本篇博客将介绍Spring Boot中异常处理的基本概念,并通过实例演示如何实现异常处理。
17 0
|
2天前
|
监控 Java Sentinel
Spring Cloud Sentinel:概念与实战应用
【4月更文挑战第28天】在分布式微服务架构中,确保系统的稳定性和可靠性至关重要。Spring Cloud Sentinel 为微服务提供流量控制、熔断降级和系统负载保护,有效预防服务雪崩。本篇博客深入探讨 Spring Cloud Sentinel 的核心概念,并通过实际案例展示其在项目中的应用。
11 0
|
4天前
|
XML Java 数据格式
手写spring第六章-实现应用上下文,完成bean的扩展机制
手写spring第六章-实现应用上下文,完成bean的扩展机制
10 0
|
6天前
|
消息中间件 Java 中间件
第十六章 Spring cloud stream应用
第十六章 Spring cloud stream应用
12 0
|
11天前
|
安全 Java UED
第5章 Spring Security 的高级认证技术(2024 最新版)(下)
第5章 Spring Security 的高级认证技术(2024 最新版)
23 0
|
11天前
|
安全 Java API
第5章 Spring Security 的高级认证技术(2024 最新版)(上)
第5章 Spring Security 的高级认证技术(2024 最新版)
38 0