当前位置:网站首页>Ad domain login authentication
Ad domain login authentication
2022-06-25 16:31:00 【GreyZeng】
author :Grey
Original address :AD Domain login authentication
demand
When the system logs in , You need to verify whether the user is a domain user by connecting to the domain server according to the user name and password .
Conditions
- Domain server address :x.x.x.x
- Domain authentication port :xxx
- AD Domain is :DC=adservice,DC=com
- A domain user is :[email protected] password :abc123.
Realization
Java edition
ADAuthJava.java
package com.hui.advalidationdemo;
import static com.hui.advalidationdemo.constant.ApplicationConstants.buildADPath;
import static com.hui.advalidationdemo.constant.ApplicationConstants.getConfig;
import static javax.naming.Context.INITIAL_CONTEXT_FACTORY;
import static javax.naming.Context.PROVIDER_URL;
import static javax.naming.Context.SECURITY_AUTHENTICATION;
import static javax.naming.Context.SECURITY_CREDENTIALS;
import static javax.naming.Context.SECURITY_PRINCIPAL;
import java.util.Hashtable;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
public class ADAuthJava {
public static boolean authenticate(String username, String password) {
DirContext ctx = null;
Hashtable<String, String> HashEnv = initADServer(username, password);
try {
ctx = new InitialDirContext(HashEnv);
System.out.println("Authenticate Success!");
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
if (null != ctx) {
try {
ctx.close();
ctx = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
private static Hashtable<String, String> initADServer(String username, String password) {
String adPath = buildADPath(username);
Hashtable<String, String> HashEnv = new Hashtable<String, String>();
HashEnv.put(SECURITY_AUTHENTICATION, "simple");
HashEnv.put(SECURITY_PRINCIPAL, adPath);
HashEnv.put(SECURITY_CREDENTIALS, password);
HashEnv.put(INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
HashEnv.put("com.sun.jndi.ldap.connect.timeout", "3000");
HashEnv.put(PROVIDER_URL, getConfig("ad.url"));
return HashEnv;
}
}
unit testing :ADAuthJavaTest.java
package com.hui.advalidationdemo;
import static com.hui.advalidationdemo.ADAuthJava.authenticate;
import static org.junit.Assert.assertTrue;
import org.junit.Test;
public class ADAuthJavaTest {
@Test
public void testAuthenticate() {
assertTrue(authenticate("abc", "abc123."));
}
}
Spring edition
Spring edition :3.2.3.RELEASE
spring-ldap-core edition :2.0.2.RELEASE
JDK1.7+
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.hui</groupId>
<artifactId>advalidationdemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>advalidationdemo</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.ldap</groupId>
<artifactId>spring-ldap-core</artifactId>
<version>2.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.acegisecurity</groupId>
<artifactId>acegi-security</artifactId>
<version>1.0.7</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>3.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>3.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>3.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>3.2.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>3.2.3.RELEASE</version>
</dependency>
</dependencies>
</project>
applicationContext-ldap.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="configBean" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location"><value>classpath:config.properties</value></property>
</bean>
<bean id="contextSource" class="org.springframework.ldap.core.support.LdapContextSource">
<property name="url" value="${ad.url}" />
<property name="base" value="${ad.base}" />
</bean>
<bean id="ldapTemplate" class="org.springframework.ldap.core.LdapTemplate">
<constructor-arg ref="contextSource" />
</bean>
<bean id="adDao" class="com.hui.advalidationdemo.ADAuthSpring">
<property name="ldapTemplate" ref="ldapTemplate" />
</bean>
</beans>
ADAuthSpring.java
package com.hui.advalidationdemo;
import static com.hui.advalidationdemo.constant.ApplicationConstants.buildADPath;
import static org.acegisecurity.ldap.LdapUtils.closeContext;
import javax.naming.directory.DirContext;
import org.springframework.ldap.core.LdapTemplate;
public class ADAuthSpring {
private LdapTemplate ldapTemplate;
public void setLdapTemplate(LdapTemplate ldapTemplate) {
this.ldapTemplate = ldapTemplate;
}
public boolean authenticate(String userName, String password) {
DirContext ctx = null;
String distinguishedName = null;
distinguishedName = buildADPath(userName);
System.out.println("userName:" + userName + " map distinguishedName:" + distinguishedName);
try {
distinguishedName = buildADPath(userName);
System.out.println("userName:" + userName + " map distinguishedName:" + distinguishedName);
ctx = ldapTemplate.getContextSource().getContext(distinguishedName, password);
System.out.println("authenticate success distinguishedName:" + distinguishedName + " userName:" + userName);
return true;
} catch (Exception e) {
System.out.println("authenticate fail distinguishedName:" + distinguishedName + " userName:" + userName);
return false;
} finally {
closeContext(ctx);
}
}
}
config.properties
# AD Validation#
ad.url=ldap://x.x.x.x:xxx
ad.base=DC=adservice,DC=com
ad.path.template=%[email protected]
unit testing :
ADAuthSpringTest.java
package com.hui.advalidationdemo;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {
"classpath:applicationContext-ldap.xml" })
public class ADAuthSpringTest {
@Autowired
public ADAuthSpring adValidation;
@Test
public void testAuth() {
Assert.assertTrue(adValidation.authenticate("abc", "123abc."));
}
}
ApplicationConstants.java
package com.hui.advalidationdemo.constant;
import static java.lang.String.format;
import static java.lang.Thread.currentThread;
import static org.apache.commons.lang3.StringUtils.isBlank;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.apache.log4j.Logger;
public class ApplicationConstants {
private static final String CONFIG_FILE = "config.properties";
private static Map<String, Object> configs = new HashMap<String, Object>();
private static final Logger log = Logger.getLogger(ApplicationConstants.class);
static {
InputStream in = null;
Properties p = new Properties();
try{
in = currentThread().getContextClassLoader().getResourceAsStream(CONFIG_FILE);
p.load(in);
for(Object k : p.keySet()){
String key = (String) k;
configs.put( key, p.getProperty(key));
}
log.info("config.properties is loaded!" );
} catch (IOException e){
log.error("Unable to read config.properties");
} finally{
if(in != null)
try {
in.close();
} catch (IOException e) {
log.error("Unable to close inputstream");
}
}
}
public static String getConfig(String key){
return (String) configs.get(key);
}
public static String buildADPath(String userName) {
String adPathTemplate = getConfig("ad.path.template");
if (isBlank(adPathTemplate)) {
log.error("ad.path template do not exist in config.properties please config it");
return null;
}
log.debug("ad.path template is "+adPathTemplate);
try {
String adPath = format(adPathTemplate, userName);
log.debug("adPath is:"+adPath);
return adPath;
} catch (Exception e) {
log.error("ad path template format error");
return null;
}
}
}
Be careful : During the test, you need to x.x.x.x,xxx,abc,123abc. Replace with the corresponding domain server ip, Domain server port , Domain user name , Domain user password
more :http://docs.spring.io/spring-ldap/docs/1.2.0/reference/
边栏推荐
- 一行代码可以做什么?
- [Third Party framework] retrofit2 (1) of network request framework -- Getting Started Guide
- Uniapp converts graphic verification codes in the form of file streams into images
- Converting cifar10 datasets
- Rxjs TakeUntil 操作符的学习笔记
- Record learning of hystrix knowledge --20210929
- File operation, serialization, recursive copy
- 这项最新的调查研究,揭开多云发展的两大秘密
- 【机器学习】基于多元时间序列对高考预测分析案例
- 10 Super VIM plug-ins, I can't put them down
猜你喜欢

心樓:華為運動健康的七年築造之旅

Day_ fifteen
Why does golang's modification of slice data affect the data of other slices?

解析数仓lazyagg查询重写优化

Geographic location data storage scheme - redis Geo

Reading mysql45 lecture - index continued

【 apprentissage automatique】 cas de prévision et d'analyse de l'examen d'entrée à l'Université basé sur des séries chronologiques multiples

10 Super VIM plug-ins, I can't put them down

Dino: Detr with improved detecting anchor boxes for end to end object detection

从TiDB上线阿里云的背后,如何看待云数据库的变革趋势
随机推荐
leetcode-8. String to integer (ATOI)
GO语言-什么是临界资源安全问题?
Data type variable operator
Problems caused by using ApplicationContext to render layout
What plug-ins are available for vscade?
Bombard the headquarters. Don't let a UI framework destroy you
Once the code was encrypted by the company's computer, the compilation failed
【NLP】今年英语高考,CMU用重构预训练交出134高分,大幅超越GPT3
Day_ fifteen
一文带你搞懂 JWT 常见概念 & 优缺点
MySQL_ JDBC
DOM event flow, event delegate
Day_ 18 hash table, generic
Alvaria announces Jeff cotten, a veteran of the customer experience industry, as its new CEO
Resolve the format conflict between formatted document and eslint
XML usage and parsing of data storage and transmission files
Helsinki traffic safety improvement project deploys velodyne lidar Intelligent Infrastructure Solution
Multiple decorators decorate a function
Deadlock, thread communication, singleton mode
Catheon gaming appointed mark Aubrey, former Asia Pacific head of Activision Blizzard, as CEO