多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
# 使用LDAP验证用户 本指南将引导您完成创建应用程序并使用 对其进行保护的过程 [Spring Security](https://projects.spring.io/spring-security/) LDAP模块 。 ## 你会建立什么 您将构建一个简单的Web应用程序,该应用程序由Spring Security的嵌入式基于Java的LDAP服务器保护。 您将使用包含一组用户的数据文件加载LDAP服务器。 ## 你需要什么 * 约15分钟 * 最喜欢的文本编辑器或IDE * [JDK 1.8](http://www.oracle.com/technetwork/java/javase/downloads/index.html) 或更高版本 * [Gradle 4+](http://www.gradle.org/downloads) 或 [Maven 3.2+](https://maven.apache.org/download.cgi) * 您还可以将代码直接导入到IDE中: * [弹簧工具套件(STS)](https://spring.io/guides/gs/sts) * [IntelliJ IDEA](https://spring.io/guides/gs/intellij-idea/) ## 如何完成本指南 像大多数Spring 一样 [入门指南](https://spring.io/guides) ,您可以从头开始并完成每个步骤,也可以绕过您已经熟悉的基本设置步骤。 无论哪种方式,您最终都可以使用代码。 要 **从头开始** ,请继续进行“ [从Spring Initializr开始”](https://spring.io/guides/gs/authenticating-ldap/#scratch) 。 要 **跳过基础知识** ,请执行以下操作: * [下载](https://github.com/spring-guides/gs-authenticating-ldap/archive/master.zip) 并解压缩本指南的源存储库,或使用 对其进行克隆 [Git](https://spring.io/understanding/Git) : `git clone [https://github.com/spring-guides/gs-authenticating-ldap.git](https://github.com/spring-guides/gs-authenticating-ldap.git)` * 光盘进入 `gs-authenticating-ldap/initial` * 继续 [创建一个简单的Web控制器](https://spring.io/guides/gs/authenticating-ldap/#initial) 。 **完成后** ,您可以根据中的代码检查结果 `gs-authenticating-ldap/complete`. ## 从Spring Initializr开始 因为本指南的重点是保护不安全的Web应用程序,所以您将首先构建不安全的Web应用程序,然后在本指南的后面,为Spring Security和LDAP功能添加更多依赖项。 如果您使用Maven,请访问 [Spring Initializr](https://start.spring.io/#!type=maven-project&language=java&platformVersion=2.4.3.RELEASE&packaging=jar&jvmVersion=1.8&groupId=com.example&artifactId=authenticating-ldap&name=authenticating-ldap&description=Demo%20project%20for%20Spring%20Boot&packageName=com.example.authenticating-ldap&dependencies=web) 以生成具有所需依赖项的新项目(Spring Web)。 以下清单显示了 `pom.xml` 选择Maven时创建的文件: ~~~ <?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.4.3</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>authenticating-ldap</artifactId> <version>0.0.1-SNAPSHOT</version> <name>authenticating-ldap</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-web</artifactId> </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> ~~~ 如果您使用Gradle,请访问 [Spring Initializr](https://start.spring.io/#!type=gradle-project&language=java&platformVersion=2.4.3.RELEASE&packaging=jar&jvmVersion=1.8&groupId=com.example&artifactId=authenticating-ldap&name=authenticating-ldap&description=Demo%20project%20for%20Spring%20Boot&packageName=com.example.authenticating-ldap&dependencies=web) 以生成具有所需依赖项的新项目(Spring Web)。 以下清单显示了 `build.gradle`选择Gradle时创建的文件: ~~~ plugins { id 'org.springframework.boot' version '2.4.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-web' testImplementation 'org.springframework.boot:spring-boot-starter-test' } test { useJUnitPlatform() } ~~~ ### 手动初始化(可选) 如果要手动初始化项目而不是使用前面显示的链接,请按照以下步骤操作: 1. 导航到 [https://start.spring.io](https://start.spring.io) 。 该服务提取应用程序所需的所有依赖关系,并为您完成大部分设置。 2. 选择Gradle或Maven以及您要使用的语言。 本指南假定您选择了Java。 3. 单击 **Dependencies,** 然后选择 **Spring Web** 。 4. 点击 **生成** 。 5. 下载生成的ZIP文件,该文件是使用您的选择配置的Web应用程序的存档。 如果您的IDE集成了Spring Initializr,则可以从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应用程序之前,应验证其是否正常运行。 为此,您需要定义一些键豆,可以通过创建一个 `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 target/gs-authenticating-ldap-0.1.0.jar ~~~ 此处描述的步骤将创建可运行的JAR。 您还可以 构建经典的WAR文件 。 如果打开浏览器并访问 [http:// localhost:8080](http://localhost:8080) ,则应该看到以下纯文本: ~~~ Welcome to the home page! ~~~ ## 设置Spring Security 要配置Spring Security,首先需要向构建中添加一些额外的依赖项。 对于基于Gradle的版本,请将以下依赖项添加到 `build.gradle` 文件: ~~~ compile("org.springframework.boot:spring-boot-starter-security") compile("org.springframework.ldap:spring-ldap-core") compile("org.springframework.security:spring-security-ldap") compile("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和一个开源LDAP服务器UnboundId。 有了这些依赖关系之后,您就可以使用纯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()` 方法配置事物,以便将登录表单中的用户名插入 `{0}` 这样它搜索 `uid={0},ou=people,dc=springframework,dc=org`在LDAP服务器中。 另外, `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](http://localhost:8080) ,则应将您重定向到Spring Security提供的登录页面。 输入用户名 `ben` 和密码为 `benspassword`。 您应该在浏览器中看到以下消息: ~~~ Welcome to the home page! ~~~ ## 概括 恭喜你! 您已经编写了一个Web应用程序,并使用 对其进行了 [Spring Security 保护](https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/) 。 在这种情况下,您使用了 [基于LDAP的用户存储](https://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#ldap) 。