본문으로 바로가기

윈도우 Active Directory 연동

category JAVA/SOURCECODE 2019. 11. 1. 17:47

Ldap 과 유사한 Activce Directory(이하 ad)

 

처음 작성한 소스는 searchFilter를 2번해서 가져온 것이였는데 그렇게까지는 필요 없어서 수정하였다.

전반적인 프로세스는 아이디와 비밀번호로 ad목록 가져올수 있는 권한을 얻고

찾는 계정에 해당하는 samAccountName 값을 가져와 개수를 출력주는 소스이다. (0 아님 1 이겠지)

 

해당 사용자가 없으면 "data 52e"" 메시지가 나오기 때문에 리턴값을 0으로 받게끔 수정해야한다.

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;

@Test
	public void adAuth() {
		String url = "LDAP://IP주소";
		
        	//환경설정
		Hashtable<String, String> env = new Hashtable<String, String>();
		env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
		env.put(Context.PROVIDER_URL, url);
		env.put(Context.SECURITY_AUTHENTICATION, "simple");
        	//사용자 계정 - 메일주소 포함
		env.put(Context.SECURITY_PRINCIPAL, "abc@abc.com");
        	//사용자 비밀번호
		env.put(Context.SECURITY_CREDENTIALS, "abc!!");
		try {
        		//찾을 사용자
			String usrId = "abc";
            		//ou - 조직 , dc - 도메인 
			String baseRdn = "ou=dev,dc=abc,dc=com";
            		//위에 환경설정으로 셋팅
			DirContext ctx = new InitialDirContext(env);
            		//결과값 필터를 미리 세팅
			SearchControls searchCtls = new SearchControls();
			//결과값 중 sn, givenName, samAccountName 항목을 보겠다는 의미
			String returnedAtts[] = { "sn", "givenName", "samAccountName" };
			searchCtls.setReturningAttributes(returnedAtts);
			//찾는 범위
			searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
			//sAMAccountName 항목이 찾을 유저와 동일한 내용만 가져옴.
			String searchFilter = String.format("(&(objectClass=user)(sAMAccountName=%s))", usrId);
			//결과값 0 아님 1
			int totalResults = 0;

			NamingEnumeration<SearchResult> answer = ctx.search(baseRdn, searchFilter, searchCtls);
			
			while (answer.hasMoreElements()) {
				SearchResult sr = (SearchResult) answer.next();
				totalResults++;
				System.out.println(">>>" + sr.getName());
				Attributes attrs = sr.getAttributes();
				System.out.println(">>>>>>" + attrs.get("samAccountName"));
			}
			//결과값 출력
			System.out.println("Total results: " + totalResults);
		} catch (NamingException e) {
			String msg = e.getMessage();
			System.out.println("msg : " + msg);
			if (msg.indexOf("data 525") > 0) {
				System.out.println("사용자를 찾을 수 없음.");
			} else if (msg.indexOf("data 773") > 0) {
				System.out.println("사용자는 암호를 재설정해야합니다.");
			} else if (msg.indexOf("data 52e") > 0) {
				System.out.println("ID와 비밀번호가 일치하지 않습니다.확인 후 다시 시도해 주십시오.");
			} else if (msg.indexOf("data 533") > 0) {
				System.out.println("입력한 ID는 비활성화 상태 입니다.");
			} else if (msg.indexOf("data 532") > 0) {
				System.out.println("암호가 만료되었습니다.");
			} else if (msg.indexOf("data 701") > 0) {
				System.out.println("AD에서 계정이 만료됨");
			} else {
				System.out.println("정상!");
			}
		}
	}

 

참고한 페이지

https://stackoverflow.com/questions/8551809/how-to-connect-with-java-into-active-directory

 

How to connect with Java into Active Directory

I am using Weblogic, Ejb3.0. Java 1.6 I need to access Active Directory via Java code. I read about several ways (Kerberos, LDAP) Anyone could advice me on comfortable way of doing so? where coul...

stackoverflow.com

ad 속성 정리

https://docs.microsoft.com/ko-kr/system-center/scsm/ad-ds-attribs?view=sc-sm-2019

 

Active Directory Domain Services 특성 Service Manager 속성 매핑

Active Directory Domain Services 특성과 Service Manager 속성 간의 관계에 알아봅니다.

docs.microsoft.com

 

'JAVA > SOURCECODE' 카테고리의 다른 글

jar 실행시 build 위치 추가  (0) 2021.03.02
Spring Security HttpSecurity, WebSecurity 차이?  (0) 2019.11.08
REST API DOCS 응용  (0) 2019.10.29
REST API DOCS  (0) 2019.10.29
반복문의 속도 개선  (0) 2019.10.27