Thursday, August 27, 2015

Active Directory Account Expiration - Java

I'm having to do some work with Active Directory accounts.  Here are some tidbits I hope are helpful.

In my situation, I am working with pwLastSet and accountExpires data which are both date/time based.

Active Directory(AD) dates in some (all?) cases are not based on the normal "C" based time functions which calculate seconds from midnight, Jan. 1st 1970.  Instead, AD uses the number of 100ns intervals from midnight, Jan. 1st 1601. 

Here is some code which calculates the number of 100ns increments between Jan 1st, 1601 and 24 hours in the future from "now".  This uses the new Java 8 date/time classes.  The initial date uses the UTC timezone and the end date is using the local timezone.  The negative 24 (-24) is because of the "minusHours()" method causing me to need to subtract a negative to get the positive(future) offset.  The duration is straight forward and by getting the seconds and multiplying by 10^7 I get the 100ns increments.  I used Math.round() just to go from double to long.  The resulting value is then usable in a context such as setting an AD account expiration.

     ZonedDateTime start = ZonedDateTime.of(1601, 1,1,0,0,0, 0, ZoneId.of("Z")); // UTC 
     LocalDateTime now = LocalDateTime.now().minusHours(-24);  
     ZonedDateTime end = ZonedDateTime.of(now, ZoneId.of("America/New_York")); // Eastern 
     Duration dur = Duration.between(start,end);  
     // result in # of 100ns increments  
     long expirationIncrements = Math.round(dur.abs().getSeconds() * Math.pow(10,7));   
     return expirationIncrements;  

Using SpringLDAP, the call to set accountExpires looks like this.  Note "expiration" here was a Long which is converted to a String for use with the LDAP API.

     final ModificationItem [] mods = new ModificationItem[]  
         {  
           new ModificationItem(DirContext.REPLACE_ATTRIBUTE, 
               new BasicAttribute("accountExpires", 
                    expiration.toString()))  
         };  
   
     ldapTemplate.modifyAttributes(userDN, mods);  

Hoping Jesus blesses your day today!
Scott

No comments:

Post a Comment