008 使用LDAP認證用戶

原文

直譯

創建一個簡單的Web控制器

在Spring中,REST端點只是Spring MVC控制器。以下Spring MVC控制器GET /通過返回一條簡單消息來處理請求:

src/main/java/hello/HomeController.java

package hello;

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!";
    }
}

整個類都被標記爲@RestControllerSpring MVC可以使用它的內置掃描功能自動檢測控制器並自動配置Web路由。

標記該方法@RequestMapping以標記路徑和REST操作。在這種情況下,GET是默認行爲; 它會返回一條消息,指示您在主頁上。

@RestController還告訴Spring MVC將文本直接寫入HTTP響應體,因爲沒有任何視圖。相反,當您訪問該頁面時,您將在瀏覽器中收到一條簡單的消息,因爲本指南的重點是使用LDAP保護頁面。

構建不安全的Web應用程序

在保護Web應用程序之前,請驗證它是否有效。爲此,您需要定義一些關鍵bean。爲此,請創建一個Application類。

src/main/java/hello/Application.java

package hello;

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

@SpringBootApplication
public class Application {

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

}

@SpringBootApplication 是一個便利註釋,添加了以下所有內容:

  • @Configuration 標記該類作爲應用程序上下文的bean定義的來源。

  • @EnableAutoConfiguration 告訴Spring Boot開始根據類路徑設置,其他bean和各種屬性設置添加bean。

  • 通常你會添加@EnableWebMvc一個Spring MVC應用程序,但Spring Boot會在類路徑上看到spring-webmvc時自動添加它。這會將應用程序標記爲Web應用程序並激活關鍵行爲,例如設置a DispatcherServlet。

  • @ComponentScan告訴Spring在包中尋找其他組件,配置和服務hello,允許它找到控制器。

該main()方法使用Spring Boot的SpringApplication.run()方法啓動應用程序。您是否注意到沒有一行XML?也沒有web.xml文件。此Web應用程序是100%純Java,您無需處理配置任何管道或基礎結構。

構建可執行的JAR

您可以使用Gradle或Maven從命令行運行該應用程序。或者,您可以構建一個包含所有必需依賴項,類和資源的可執行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,您應該看到以下純文本:

Welcome to the home page!

設置Spring Security

要配置Spring Security,首先需要爲構建添加一些額外的依賴項。

對於基於Gradle的構建:

build.gradle

dependencies {
    compile("org.springframework.boot:spring-boot-starter-web")
    compile("org.springframework.boot:spring-boot-starter-security")
    compile("org.springframework.ldap:spring-ldap-core")
    compile("org.springframework.security:spring-security-ldap")
    compile("org.springframework:spring-tx")
    compile("com.unboundid:unboundid-ldapsdk")
    testCompile("org.springframework.boot:spring-boot-starter-test")
    testCompile("org.springframework.security:spring-security-test")
}

由於Gradle的工件解析問題,必須拉入spring-tx或Gradle將獲取不起作用的舊版本。
對於基於Maven的構建:

pom.xml

<dependencies>
    <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.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>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

這些依賴項添加了Spring Security和UnboundId,一個開源LDAP服務器。有了這些,您就可以使用純Java來配置安全策略。

src/main/java/hello/WebSecurityConfig.java

package hello;

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.password.LdapShaPasswordEncoder;

@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 LdapShaPasswordEncoder())
					.passwordAttribute("userPassword");
	}

}

在@EnableWebSecurity對各種使用Spring安全所需豆圈。

您還需要一個LDAP服務器。Spring Boot提供了用純Java編寫的嵌入式服務器的自動配置,該服務器正在用於本指南。該ldapAuthentication()方法配置登錄表單中的用戶名插入的內容{0},以便uid={0},ou=people,dc=springframework,dc=org在LDAP服務器中進行搜索。此外,該passwordCompare()方法配置編碼器和密碼屬性的名稱。

設置用戶數據

LDAP服務器可以使用LDIF(LDAP數據交換格式)文件來交換用戶數據。允許Spring Boot 的spring.ldap.embedded.ldif屬性application.properties拉入LDIF數據文件。這樣可以輕鬆預加載演示數據。

src/main/resources/test-server.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: {SHA}nFCebWjxfaLbHHG1Qk5UU4trbvQ=

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的用戶存儲。

延伸知識

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章