---
title: "EJB 3 Security Domain with Open LDAP"
author: "seaboycs"
date: "2014-01-14T15:42:24Z"
tags: ["JBoss"]
categories: ["企业架构"]
slug: "ejb-3-security-domain-with-open-ldap"
draft: false
lastmod: "2014-01-15T08:19:15Z"
id: 2003828
url: "https://seaboycs.iteye.com/blog/2003828"
---

项目中用到了EJB 3 web service, 生产环境上都是有安全认证的，常见的认证有2中，一种是数据库认证，另外一种是LDAP认证。这篇文章主要讲述的是LDAP认证，使用的LDAP是openLDAP windows版本。

 

**准备条件：**

1\. 服务器: JBoss 6 (自行下载)

2\. LDAP:  Open LDAP for windows （参考网络，很多文档）

3\. Maven 依赖：jboss-ejb3-ext-api, jboss-ejb-api, jboss-as-system-jmx

 

**LDAP 配置**

1\. 依照网络上的通用例子新建一个xx.ldif文件，密码就设置成admin或者其他的，

```
dn: dc=example,dc=com
objectclass: dcObject
objectclass: organization
o: Example Company
dc: example

dn: cn=Manager,dc=example,dc=com
objectclass: organizationalRole
cn: Manager
```

 

2\. 添加2个ou(Users, Roles)：

```
dn: ou=Users,dc=example,dc=com
objectclass: organizationalRole
objectclass: top

dn: ou=Roles,dc=example,dc=com
objectclass: organizationalRole
objectclass: top
```

 

3\. 添加1个测试用户和1个测试角色

```
dn: uid=tester,ou=Users,dc=example,dc=com
objectclass: top
objectclass: inetOrgPerson
objectclass: person
uid: tester
cn: tester
sn: tester
userPassword:1

dn: cn=test,ou=Users,dc=example,dc=com
objectClass: top
objectClass: groupOfNames
cn: test
description: testgroup
member: uid=tester,ou=Users,dc=example,dc=com
```

 **注意：objectClass一定要匹配，不要弄错了。**

 

再添加一个普通用户，不要加入到test组中，

 

```
dn: uid=tester2,ou=Users,dc=example,dc=com
objectclass: top
objectclass: inetOrgPerson
objectclass: person
uid: tester
cn: tester
sn: tester
userPassword:1
```

 

**配置JBoss login config xml**

1\. 打开jboss-6\\server\\default\\conf\\login-config.xml, 在 &lt;application-policy name="other"&gt;之前添加一段：

```
<application-policy name="sd">
		<authentication>
			<login-module code="org.jboss.security.auth.spi.LdapExtLoginModule"
				flag="required">
				<module-option name="java.naming.factory.initial">com.sun.jndi.ldap.LdapCtxFactory</module-option>
				<module-option name="java.naming.security.authentication">simple</module-option>
				<module-option name="java.naming.provider.url">ldap://example.com:389</module-option>
				<module-option name="bindDN">cn=Manager,dc=example,dc=com</module-option>
				<module-option name="bindCredential">admin</module-option>
				<module-option name="baseCtxDN">ou=Users,dc=example,dc=com</module-option>
				<module-option name="baseFilter">(uid={0})</module-option>
				<module-option name="rolesCtxDN">ou=roles,dc=example,dc=com</module-option>
				<module-option name="roleFilter">(member={1})</module-option>
				<module-option name="roleAttributeID">cn</module-option>
			</login-module>

		</authentication>
	</application-policy>
```

 

**新建MAVEN项目**

项目名：securityTest

 

pom.xml:

 

```
<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 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.javaeye.ejb</groupId>
  <artifactId>securityTest</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>ejb</packaging>
  <properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>
	<dependencies>	
		<dependency>
			<groupId>org.jboss.ejb3</groupId>
			<artifactId>jboss-ejb3-ext-api</artifactId>
			<version>1.1.1</version>
		</dependency>
		<dependency>
			<groupId>org.jboss.javaee</groupId>
			<artifactId>jboss-ejb-api</artifactId>
			<version>3.0.0.CR1</version>
		</dependency>
		<dependency>
			<groupId>org.jboss.jbossas</groupId>
			<artifactId>jboss-as-system-jmx</artifactId>
			<version>6.0.0.M1</version>
		</dependency>
	</dependencies>

	<build>
		<finalName>securityTest</finalName>
		<resources>
			<resource>
				<directory>src/main/resources</directory>
				<filtering>true</filtering>
			</resource>
		</resources>
		<plugins>
		<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.3.2</version>
				<configuration>
					<source>1.6</source>
					<target>1.6</target>
					<encoding>utf8</encoding>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-ejb-plugin</artifactId>
				<version>2.3</version>
				<configuration>
					<ejbVersion>3.0</ejbVersion>
				</configuration>
			</plugin>			
		</plugins>
	</build>
</project>
```

 

 

**Service Interface:**

 

```
package com.javaeye.test;

import javax.jws.WebService;
import javax.jws.soap.SOAPBinding;

@WebService(targetNamespace = "http://www.javaeye.com/test/", name = "test")
@SOAPBinding(parameterStyle = SOAPBinding.ParameterStyle.BARE)
public interface Test {

	public String process(String parameters);
}
```

 

 

**Service Impl**

 

```
package com.javaeye.ejb;

import javax.annotation.security.RolesAllowed;
import javax.ejb.Stateless;
import javax.jws.WebService;

import org.jboss.ejb3.annotation.SecurityDomain;
import org.jboss.wsf.spi.annotation.WebContext;

import com.javaeye.test.Test;

@Stateless
@WebService(serviceName = "Test", endpointInterface = "com.javaeye.test.Test", targetNamespace = "http://www.javaeye.com/test/")
@WebContext(contextRoot = "securityTest", urlPattern = "/test", authMethod = "BASIC", secureWSDLAccess = true)
@SecurityDomain("sd")
public class SecurityTestService implements Test{

	@RolesAllowed({ "test" })
	public String process(String parameters) {
		return "Hello, " + parameters;
	}

}
```

 

 

Service 很简单，就是一个hello + input。![酷](http://www.iteye.com/javascripts/tinymce/plugins/emotions/img/smiley-cool.gif "酷")

执行 mvn clean install, 在target会生成一个jar包，把架包丢到jboss deploy目录下，启动jboss， 可以看到service注册成功：

 

```
15:31:41,069 INFO  [org.jboss.wsf.stack.cxf.metadata.MetadataBuilder] Add Service
 id=SecurityTestService
 address=http://localhost:9000/securityTest/test
 implementor=com.javaeye.ejb.SecurityTestService
 invoker=org.jboss.wsf.stack.cxf.InvokerEJB3
 serviceName={http://www.javaeye.com/test/}Test
 portName={http://www.javaeye.com/test/}SecurityTestServicePort
 wsdlLocation=null
 mtomEnabled=false
```

 

 

通过soup ui新建一个project， wsdl：http://localhost:9000/securityTest/test?wsdl

回车后要求输入用户和密码，则填入：tester/1,回车后打开项目，双击process方法下面的Request 1

 

Input:

 

```
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:test="http://www.javaeye.com/test/">
   <soapenv:Header/>
   <soapenv:Body>
      <test:process>aaa</test:process>
   </soapenv:Body>
</soapenv:Envelope>
```

 

 

 case 1： 在SOAP UI Reuest Property里面设置Username=tester, Password=1, (正确的用户，有正确的权限)然后执行方法，将返回

 

```
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
   <soap:Body>
      <processResponse xmlns="http://www.javaeye.com/test/">Hello, aaa</processResponse>
   </soap:Body>
</soap:Envelope>
```

 

 

case 2: 在SOAP UI Reuest Property里面设置Username=tester, Password=12, (错误的用户密码)然后执行方法，将返回

 

```
<html><head><title>JBoss Web/3.0.0-CR1 - Error report</title><style><!--H1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} H2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} H3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} BODY {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} B {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} P {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;}A {color : black;}A.name {color : black;}HR {color : #525D76;}--></style> </head><body><h1>HTTP Status 401 - </h1><HR size="1" noshade="noshade"><p><b>type</b> Status report</p><p><b>message</b> <u></u></p><p><b>description</b> <u>This request requires HTTP authentication ().</u></p><HR size="1" noshade="noshade"><h3>JBoss Web/3.0.0-CR1</h3></body></html>
```

 

 

case 3: 在SOAP UI Reuest Property里面设置Username=tester2, Password=1, (正确的用户，没有权限)然后执行方法，将返回

 

```
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
   <soap:Body>
      <soap:Fault>
         <faultcode>soap:Server</faultcode>
         <faultstring>Caller unauthorized</faultstring>
      </soap:Fault>
   </soap:Body>
</soap:Envelope>
```

 

至此，测试完毕。谢谢阅读！