springboot官方例子--使用Spring Security和LDAP对用户进行身份验证

本次讲的内容是,使用Spring Security和LDAP对用户进行身份验证,你将学到Spring Security知识,这是一个非常常用的安全框架(另外一个是 shiro);然后你将学到LDAP,这是一个非常轻量目录访问协议,特别适合如部门信息号工等这种有层次结构的树形数据。

我利用业余时间,翻译了Spring官网的例子,方便中文不好的同学,将陆续发到头条上,欢迎大家关注,也可以上我个人BLOG:itmanclub.com,上面有已经翻译过的。
在这里插入图片描述

springboot官方例子–对用户进行身份验证
正方代码如下:

程序结构

└── src
 └── main
 └── java
 └── hello

pom.xml文件

<?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>
 <groupId>org.springframework</groupId>
 <artifactId>gs-authenticating-ldap</artifactId>
 <version>0.1.0</version>
 <parent>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-starter-parent</artifactId>
 <version>2.1.6.RELEASE</version>
 </parent>
 <properties>
 <java.version>1.8</java.version>
 </properties>
 <!-- tag::security[] -->
 <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>
 <!-- end::security[] -->
 <build>
 <plugins>
 <plugin>
 <groupId>org.springframework.boot</groupId>
 <artifactId>spring-boot-maven-plugin</artifactId>
 </plugin>
 </plugins>
 </build>
</project>

Spring Boot将会你做如下的事:

将 classpath 里面所有用到的jar包构建成一个可执行的 JAR 文件,方便执行你的程序
搜索public static void main()方法并且将它当作可执行类
根据springboot版本,去查找相应的依赖类版本,当然你可以定义其它版本。
创建一个简单的web控制器

在Spring中,REST端点就是SpringMVC控制器。以下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!";
 }
}

整个类都标记了@RestController,因此SpringMVC可以使用其内置的扫描功能自动检测控制器,并自动配置Web路由。

该方法用 @GetMapping标记,用以标记路径和REST操作。在这种情况下,默认行为是GET,它返回一条消息。

@RestController还告诉SpringMVC直接将文本写入HTTP响应主体,因为没有任何视图。本指南在你访问页面时,您将在浏览器中收到一条简单的消息,因为本次重点是使用LDAP保护页面。

创建一个不安全web应用

在保护Web应用程序之前,请验证它是否正常工作。要做到这一点,您需要定义一些关键bean。为此,创建一个应用程序类。

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 告诉SpringBoot根据类路径设置、其他bean和各种属性设置开始添加bean。
  • @ComponentScan 告诉Spring在hello包中查找其他组件、配置和服务。

您注意到没有一行XML吗?也没有web.xml文件。这个Web应用程序是100%纯Java,您不必麻烦的基础配置。

SpringBoot支持内存中的关系数据库引擎H2,并自动创建连接。因为我们使用的是SpringJDBC,所以SpringBoot会自动创建一个JDBCTemplate。@Autowired JdbcTemplate字段自动加载并使其可用。

** 运行你的程序(STS下,Maven可参考前面文章)**

右键-选择Run as-Spring Boot App:

打开浏览器访问 http://localhost:8080, 你会看到如下的内容:

Welcome to the home page!
设置Spring Security

要配置Spring安全性,首先需要添加一些额外的依赖项。

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。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 Security所需的各种bean。

您还需要一个LDAP服务器。Spring boot提供了一个自动配置的、纯Java编写的嵌入式服务器,我们本次用这个。 ldapAuthentication()方法配置登录表单的用户名插入{0}的位置,

以便在LDAP服务器中搜索uid={0},ou=people,dc=springframework,dc=org。此外,passwordCompare()方法还配置编码器和密码属性的名称。

设置用户数据

LDAP服务器可以使用LDIF(LDAP数据交换格式)文件来交换用户数据。application.properties中的spring.ldap.embedded.ldif属性允许Springboot导入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和密码:bensapsword。您应该在浏览器中看到此消息:

Welcome to the home page!

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值