Authentication on Active Directory using JNDI (A Proffessional Appraoch)

I am using following code for getting authenticated on Active Directory by user logon name.
Can any one tell me a more proffessional and fool proof appraoch for authenticating a user on Active Dir through my web interface ???
thanks in advance
* Created on Nov 10, 2004
package auth;
import java.util.Hashtable;
import javax.naming.AuthenticationException;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
* @author Tushar Agrawal
* Created On Nov 10, 2004
public class UserAuthentication {
     public UserAuthentication() {
          super();
     public NamingEnumeration loginToActiveDirectory(
          String logonName,
          String password,
          String domain) {
          boolean success = false;
          NamingEnumeration attrs = null;
          Hashtable env = new Hashtable(11);
          env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
          env.put(Context.SECURITY_AUTHENTICATION, "simple");
          env.put(Context.PROVIDER_URL, "ldap://domain:389/dc=SECLORE,dc=com");
          env.put(Context.SECURITY_PRINCIPAL, logonName + "@" + domain);
          env.put(Context.SECURITY_CREDENTIALS, password);
          //env.put(Context.SECURITY_PROTOCOL, "ssl");
          env.put("java.naming.ldap.version", "3");
          env.put(Context.REFERRAL, "follow");
          try {
               String base = "";
               DirContext ctx = new InitialDirContext(env);
               SearchControls controls = new SearchControls();
               controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
               controls.setReturningAttributes(
                    new String[] {
                         "sAMAccountName",
                         "userPrincipalName",
                         "displayName",
                         "memberOf",
                         "objectSid",
                         "title" });
               NamingEnumeration e =
                    ctx.search(base, "sAMAccountName=" + logonName, controls);
               if (e.hasMore()) {
                    SearchResult r = (SearchResult) e.next();
                    attrs = r.getAttributes().getAll();
                    /*while (attrs.hasMore()) {
                         System.out.println(attrs.next());
                    ctx.close();
          } catch (AuthenticationException e) {
               System.err.println("Problem getting attribute: " + e);
               success = false;
          } catch (NamingException e) {
               System.err.println("Problem getting attribute: " + e);
               success = false;
          return attrs;
tushar agrawal

You''l find more info at :
http://jakarta.apache.org/tomcat/tomcat-5.5-doc/catalina/funcspecs/fs-jndi-realm.html
http://jakarta.apache.org/tomcat/tomcat-4.0-doc/realm-howto.html
That's the right way to do it.

Similar Messages

  • Querying deleted objects container in Active Directory using JNDI

    Hi,
    I am trying to query deleted objects container using JNDI which fails with error 64.
    Has anyone seen this or knows how to query AD using binary data in JNDI.
    Seems to me there is some problem with the search base.
    search base: <GUID=18E2EA80684F11D2B9AA00C04F79F805,dc=engserver,dc=com>.
    filter: objectclass=*
    search scope: subtree
    This is the error:
    Search example failed.
    javax.naming.InvalidNameException: <GUID=18E2EA80684F11D2B9AA00C04F79F805,dc=eng
    server,dc=com>: [LDAP: error code 64 - 00000057: LdapErr: DSID-0C090563, comment
    : Error processing name, data 0, v893 ]; remaining name '<GUID=18E2EA80684F11D2B
    9AA00C04F79F805,dc=engserver,dc=com>'
    at com.sun.jndi.ldap.LdapCtx.processReturnCode(LdapCtx.java:2802)
    at com.sun.jndi.ldap.LdapCtx.processReturnCode(LdapCtx.java:2616)
    at com.sun.jndi.ldap.LdapCtx.searchAux(LdapCtx.java:1744)
    at com.sun.jndi.ldap.LdapCtx.c_search(LdapCtx.java:1667)
    at com.sun.jndi.toolkit.ctx.ComponentDirContext.p_search(ComponentDirCon
    text.java:368)
    at com.sun.jndi.toolkit.ctx.PartialCompositeDirContext.search(PartialCom
    positeDirContext.java:328)
    at com.sun.jndi.toolkit.ctx.PartialCompositeDirContext.search(PartialCom
    positeDirContext.java:313)
    at javax.naming.directory.InitialDirContext.search(InitialDirContext.jav
    a:245)
    at jSearch.main(jSearch.java, Compiled Code)
    Thanks,
    Chetan

    I thought I had posted one of these. How remiss of me !/**
    * deleted.java
    * 5 July 2001
    * Sample JNDI application to search for deleted objects
    * Modified December 2004 to add Win2K3 lastKnownParent
    import java.util.Hashtable;
    import javax.naming.*;
    import javax.naming.ldap.*;
    import javax.naming.directory.*;
    import com.sun.jndi.ldap.ctl.*;
    class DeletedControl implements Control {
         public byte[] getEncodedValue() {
              return new byte[] {};
         public String getID() {
              return "1.2.840.113556.1.4.417";
         public boolean isCritical() {
              return true;
    public class deleted     {
         public static void main (String[] args)     {
              Hashtable env = new Hashtable();
              String adminName = "CN=Administrator,CN=Users,DC=ANTIPODES,DC=COM";
              String adminPassword = "XXXXXX";
              String ldapURL = "ldap://mydc.antipodes.com:389";
              env.put(Context.INITIAL_CONTEXT_FACTORY,"com.sun.jndi.ldap.LdapCtxFactory");
              //set security credentials, note using simple cleartext authentication
              env.put(Context.SECURITY_AUTHENTICATION,"simple");
              env.put(Context.SECURITY_PRINCIPAL,adminName);
              env.put(Context.SECURITY_CREDENTIALS,adminPassword);
              //connect to my domain controller
              env.put(Context.PROVIDER_URL,ldapURL);
              try {
                   //Create the initial directory context
                   LdapContext ctx = new InitialLdapContext(env,null);
                   //Create the search controls           
                   SearchControls searchCtls = new SearchControls();
                   //Specify the attributes to return
                   String returnedAtts[]={"distinguishedName","lastKnownParent"};
                   searchCtls.setReturningAttributes(returnedAtts);
                   //Specify the search scope
                   searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
                   //specify the LDAP search filter
                   String searchFilter = "(&(objectClass=user)(isDeleted=TRUE))";
                   //Specify the Base for the search
                   String searchBase = "DC=antipodes,DC=com";
                   //initialize counter to total the results
                   int totalResults = 0;
                   //specify the Deleted control
                   Control[] rqstCtls = new Control[] {new DeletedControl()};
                   ctx.setRequestControls(rqstCtls);
                   //Search for objects using the filter
                   NamingEnumeration answer = ctx.search(searchBase, searchFilter, searchCtls);
                   //Loop through the search results
                   while (answer.hasMoreElements()) {
                        SearchResult sr = (SearchResult)answer.next();
                        totalResults++;
                        System.out.println(totalResults + ". " + sr.getName().toString());
                        // Print out some of the attributes, catch the exception if the attributes have no values
                        Attributes attrs = sr.getAttributes();
                        if (attrs != null) {
                             try {
                                  for (NamingEnumeration ae = attrs.getAll();ae.hasMore();) {
                                       Attribute attr = (Attribute)ae.next();
                                       System.out.println("Attribute: " + attr.getID());
                                       for (NamingEnumeration e = attr.getAll();e.hasMore();System.out.println("   " + e.next().toString()));
                             catch (NullPointerException e)     {
                             System.err.println("Problem listing attributes: " + e);
                   System.out.println("Deleted objects: " + totalResults);
                   ctx.close();
              catch (NamingException e) {
              System.err.println("Problem searching directory: " + e);
    }

  • Creating MailBox-enabled Users In Active Directory Using JNDI

    Thanks to the Various code samples i have come across in this forum i have been able to use the JNDI API to add a new user to the Microsoft Active directory.
    The user account that was added using a combination of the various code samples was already enabled. but the problem is that the user does not have an Exchange MailBox created/enabled as well.
    When attempts were made to access the users IMAP mailbox from an external webmail client, the following message:
    "No Such Object On The Server"
    Was Recieved.
    I am wondering wether there is an attribute i am missing out. or something.
    i would welcome any suggestions.
    please treat as urgent.
    thank you in anticipation
    Below is the list of attributes i set:
    BasicAttributes ba=new BasicAttributes();
    ba.put(new BasicAttribute("userPrincipalName","[email protected]"));
    ba.put(new BasicAttribute("sAMAccountName","fagu"));
    ba.put(new BasicAttribute("title","Anyhow"));
    ba.put(new BasicAttribute("mail","[email protected]"));
    ba.put(new BasicAttribute("mailNickname","fagu"));
    ba.put(new BasicAttribute("objectClass","user"));
    ba.put(new BasicAttribute("displayName","Festus Agu"));
    ba.put(new BasicAttribute("sn","Agu"));
    ba.put(new BasicAttribute("userAccountControl","66048"));
    //ba.put(new BasicAttribute("unicodePwd ","fagu"));
    ba.put(new BasicAttribute("mDBUseDefaults","TRUE"));
    ba.put(new BasicAttribute("homeMTA","CN=Microsoft MTA,CN=XSOCKET2,CN=Servers,CN=First Administrative Group,CN=Administrative Groups,CN=SocketWorks,CN=Microsoft Exchange,CN=Services,CN=Configuration,DC=socketworkscorp,DC=localdomain"));
    ba.put(new BasicAttribute("msExchHomeServerName", "/o=SocketWorks/ou=First Administrative Group/cn=Configuration/cn=Servers/cn=XSOCKET2"));
    ba.put(new BasicAttribute("distinguishedName","CN=Festus"));

    I am trying to create a MailBox enabled user in AD.I am setting all the attributes that are mentioned above.
    Still i am unable to create a user.I guess i am messing up with password and getting error "javax.naming.OperationNotSupportedException: [LDAP: error code 53 - 00002077: SvcErr: DSID-031D0AAB,
    problem 5003 (WILL_NOT_PERFORM), data 0"
    Is it that SSL is must to create a user.I saw a certificate on Exchange server.But i am using a simple protocal to create a user.
    Please help me with the steps needed to create a user if i have to use SSL or is there is any settings to be turned on the server.
    Thanks!!
                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • How to set up authentication against Active Directory using custom account

    Hi All,
    Our development BPC server (version 7.0.112, MSSQL Server 2005) was installed using a local user in domain X. It is a single-server installation (meaning all services were installed on that server). The dev server always has the latest data/users by restoring the production backup on the dev server. For testing purpose, I need to allow a user of domain X to log in and do a testing.
    Is there a way to configure the dev server to authenticate against an Active Directory in domain X using a special user in the domain X? If yes, how can I configure the dev server?
    Thanks.

    The installation user must be a domain user with rights to browse domain X.
    Otherwise you are not able to add users fom domain.
    In your case installation was done with a local user which means you willnot be able to use domain users.
    It can be an workaround if you will change the identity for 2 COM+ components to be a domain user instead to be that local user.
    Any way I don't advice you to do this. It will be better to reinstall the dev using a domain user.
    The COM+ which has to be changed are:
    OsoftAdminServer
    OsoftUserManage
    Attention domain user used must be added into administartor group of BPC server and also to have sys admin right to SQL Server.
    I hope this will help you.
    Regards
    Sorin Radulescu

  • Cisco ISE (Authentication failed: 24415 User authentication against Active Directory failed since user's account is locked out)

    Hi,
    I have a setup ISE 1.1.1. Users are getting authenticate against AD. Everything is working fine except some users report disconnection. I see in the ISE that (Authentication failed: 24415 User authentication against Active Directory failed since user's account is locked out). Users are using Windows 7 OS.
    Error is enclosed & here is the port configuration.
    Port Configuration.
    interface GigabitEthernet0/2
    switchport access vlan 120
    switchport mode access
    switchport voice vlan 121
    authentication event fail action next-method
    authentication event server dead action reinitialize vlan 120
    authentication event server alive action reinitialize
    authentication host-mode multi-auth
    authentication order mab dot1x
    authentication priority dot1x mab
    authentication port-control auto
    authentication periodic
    authentication timer reauthenticate server
    mab
    dot1x pae authenticator
    dot1x timeout tx-period 60
    spanning-tree portfast
    ip dhcp snooping limit rate 30 interface GigabitEthernet0/2
    switchport access vlan 120
    switchport mode access
    switchport voice vlan 121
    authentication event fail action next-method
    authentication event server dead action reinitialize vlan 120
    authentication event server alive action reinitialize
    authentication host-mode multi-auth
    authentication order mab dot1x
    authentication priority dot1x mab
    authentication port-control auto
    authentication periodic
    authentication timer reauthenticate server
    mab
    dot1x pae authenticator
    dot1x timeout tx-period 60
    spanning-tree portfast
    ip dhcp snooping limit rate 30
    Please help.

    The error message means that Active Directory server Reject the authentication attempt
    as for some reasons the user account got locked.I guess, You should ask your AD Team to check in the AD
    Event Logs why did the user account got locked.
    Under Even Viewers, You can find it out
    Regards
    Minakshi (Do rate the helpful posts)

  • Cisco ISE Failure: 24408 User authentication against Active Directory failed since user has entered the wrong password

    Hi,
    Since we implemented Cisco ISE we receive the following failure on several Notebooks:
    Authentication failed : 24408 User authentication against Active Directory failed since user has entered the wrong password
    This happens 2 or 3 times per Day. So basically the authentications are working. But when the failure appears, the connection is lost for a short time.
    The Clients are using PEAP(EAP-MSCHAPv2) for Authentication. We've got a Cisco Wireless Environment (WLC 5508).
    Why is this happening?
    Thanks,
    Marc

    The possible causes of this error message are:
    1.] If the end user entered an incorrect username.
    2.] The shared sceret between WLC and ISE is mismatched. With this we'll see continous failed authentication.
    3.] As long as a PSN not receiving a response from the supplicant within this limit during an EAP conversation, it will throw this error code. In majority of cases it says eap session timed out.
    In your cases, the 3rd option seems to be the most closest one.
    Jatin Katyal
    - Do rate helpful posts -

  • T5-2 ILOM authentication via Active Directory

    Hello,
    We are trying to leverage AD to authenticate our ILOMs. However I am seeing the following when I set the method to None (server authentication)
    (ActDir) ServerUserAuth - Error 0, failed to validate user group access
    We have a group defined and I have set it under Admin groups using the DN.
    Any ideas on this or has anyone been successful getting this to work with AD and AD Groups?
    TIA.
    Jeff

    Hello Man !
    your provided documents and links are very effective. thank you guy for your help. right now i have to problem below listed,
    I have Cisco aironet 1142n access point. I have no ACS / WLC
    but want to authenticate end users 802.1x with Active directory 2003/2008 using RADIUS (IAS/NPS).
    These APs are standalone. Please provide any configuration document
    "How to authenticate end users with active directory using cisco 1142n Standalone (Without WLC/ACS)".
    Thanks & Regards,
    Rizwan Haider Siddiqui.

  • Problem in provisioning user from oim to active directory using ssl

    hi,
    problem in provisioning user from oim to active directory using ssl i am getting following error while provisioning user to AD.
    15:18:12,984 ERROR [ADCS] Communication Errorsimple bind failed: 172.16.30.35:636
    15:18:12,984 ERROR [ADCS] The error occured in tcADUtilLDAPController::connectTo
    AvailableAD():simple bind failed: 172.16.30.35:636
    15:18:13,015 ERROR [SERVER] Class/Method: tcProperties/tcProperties encounter so
    me problems: Must set a query before executing
    com.thortech.xl.dataaccess.tcDataSetException: Must set a query before executing
    at com.thortech.xl.dataaccess.tcDataSet.checkExecute(Unknown Source)
    at com.thortech.xl.dataaccess.tcDataSet.executeQuery(Unknown Source)
    at com.thortech.xl.dataobj.tcDataSet.executeQuery(Unknown Source)
    at com.thortech.xl.dataaccess.tcDataSet.executeQuery(Unknown Source)
    at com.thortech.xl.dataobj.tcDataSet.executeQuery(Unknown Source)
    at com.thortech.xl.dataobj.util.tcProperties.<init>(Unknown Source)
    at com.thortech.xl.dataobj.util.tcProperties.initialize(Unknown Source)
    at Thor.API.tcUtilityFactory.getLocalUtility(Unknown Source)
    at Thor.API.tcUtilityFactory.getUtility(Unknown Source)
    at com.thortech.xl.integration.ActiveDirectory.tcADUtilLDAPController.co
    nnectToAvailableNextAD(Unknown Source)
    at com.thortech.xl.integration.ActiveDirectory.tcADUtilLDAPController.se
    archResultPageEnum(Unknown Source)
    at com.thortech.xl.schedule.tasks.ADLookupRecon.performReconciliation(Un
    known Source)
    at com.thortech.xl.schedule.tasks.ADLookupReconTask.execute(Unknown Sour
    ce)
    at com.thortech.xl.scheduler.tasks.SchedulerBaseTask.run(Unknown Source)
    at com.thortech.xl.scheduler.core.quartz.QuartzWrapper$TaskExecutionActi
    on.run(Unknown Source)
    at Thor.API.Security.LoginHandler.jbossLoginSession.runAs(Unknown Source
    at com.thortech.xl.scheduler.core.quartz.QuartzWrapper.execute(Unknown S
    ource)
    at org.quartz.core.JobRunShell.run(JobRunShell.java:203)
    at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.j
    ava:520)
    can any one help.
    Thanks and Regards,
    praveen,

    Are you able to connect to AD over SSL through some LDAP Browser ?
    Check the validity of Certificate ?
    Does your certificate appear in the list ?

  • How to save HR data in Active Directory using ABAP i.e thru LDAP Connector

    Hi All,
           Can any one please help me out how
           to save HR data in Active directory
           using LDAP Connector ?             
           Please help ASAP as it is very urgent .
    Thanks
    Jitendra

    There are 100 of such scripts are there online.
    here are few tips and codes. you will get more.  
    https://gallery.technet.microsoft.com/scriptcenter/Feeding-data-to-Active-0227d15c
    http://blogs.technet.com/b/heyscriptingguy/archive/2012/10/31/use-powershell-to-modify-existing-user-accounts-in-active-directory.aspx
    http://powershell.org/wp/forums/topic/ad-import-csv-update-attributes-script/
    Please mark this as answer if it helps

  • How to save hr data in Active directory  using abap

    Hi all
    can any one please help me out how to save hr data in Active directory using LDAP connector
    please help as this is very urgent requirement
    thanks in advance
    Thanks
    Chanti

    What form do you have the user's name in ?
    ANTIPODES\alberteString searchFilter = "(&(objectClass=user)(samAccountName=alberte))";[email protected] searchFilter = "(&(objectClass=user)(userPrincipalName=[email protected]))";Albert EinsteinString searchFilter = (&(objectClass=user)(givenName=Albert)(sn=Einstein))";or using Ambiguous Name Resolution (anr)String searchFilter = "(&(objectClass=user)(anr=Albert Einstein))";or it's even clever enough to useString searchFilter = "(&(objectClass=user)(anr=Einstein Albert))";

  • Please Help.  How can you monitor a directory using jndi connection to a ldap server?

    How can you monitor a directory using jndi connection to a ldap server? I
    want the ldap server to monitor the content change in a file system
    directory on another computer on the network. Can someone please help.
    Thanks
    Fred

    Hi,
    Why do you want to use LDAP for Hard disk monitoring..???
    U can do this by creating a MD5 checksum for all the files existing in some
    perticular
    directory and every hour or any configurable period u can recalculate the
    checksum
    to find out the change in the content.
    I guess all u need is to get the code for "updatedb" utility of Linux and
    instrument it for ur needs..
    Hope it helps...
    -aseem
    mr wrote:
    How can you monitor a directory using jndi connection to a ldap server? I
    want the ldap server to monitor the content change in a file system
    directory on another computer on the network. Can someone please help.
    Thanks
    Fred

  • Filtering Groups on Windows Active Directory using LDAP Authentication

    Hi All,
    I have small module that filters the groups from the Windows AD using LDAP attributes and flushes the data into the DB[code below].
    This module was developed and tested on weblogic 8.1[on windows]and works fine.
    Now the same is moved to another environment- Websphere on Linux Suse. The code fails to retreieve any value from the Windows AD.
    Please note no exception is aslo thrown.
    env.put(Context.INITIAL_CONTEXT_FACTORY,ldapCtxFactory);
              //set security credentials, note using simple cleartext authentication
              env.put(Context.SECURITY_AUTHENTICATION,authentication);
              env.put(Context.SECURITY_PRINCIPAL,adminName);
              env.put(Context.SECURITY_CREDENTIALS,adminPassword);
              //connect to my domain controller
              env.put(Context.PROVIDER_URL, domainController);
              // Create the initial directory context
              try {
                                  dirCtx = new InitialDirContext(env);
                   // Create the search controls           
                   SearchControls searchCtls = new SearchControls();
                   //Specify the attributes to return
                   String returnedAtts[]={"member"};
                   searchCtls.setReturningAttributes(returnedAtts);
                   //Specify the search scope
                   searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);
                   int totalResults = 0;
                   int iteration=0;
                   // Search for objects using the filter
                   NamingEnumeration results = ctx.search(searchBase, searchFilter, searchCtls);
    In the above code the method exits even before the try block[i could detect this using Sysout's]
    Below is the property file from which the values are read.
    admin=username
    password=password
    #AD search attributes
    searchBase=DC=domainname,DC=domainname
    searchFilter=(&(objectClass=group) (CN=value*))
    #JNDI context attributes
    ldapCtxFactory=com.sun.jndi.ldap.LdapCtxFactory
    authentication=simple
    domainController=ldap://address
    groupPattern=pattern
    Please Assit,
    Thanks in Advance
    Message was edited by:
    radiant
    Message was edited by:
    radiant

    Assuming it is the same Active Directory environment and only your Java platform has changed, the I can only assume that if no exception is thrown, and no data is returned, then the credentials you are using on the new Java platform are being mapped to an anonymous user (perhaps a blank password ?). By default, Windows Server 2003 domains, do not return any results to anonymous users.

  • Changing user password in Active Directory using the JNDI GSS-API/Kerberos5

    Hello,
    I am trying to the JNDI GSS-API to change a user password on an Active Directory Server 2003. I have seen a variation of this using SSL on the thread [*http://forums.sun.com/thread.jspa?threadID=592611&start=0&tstart=0*|http://forums.sun.com/thread.jspa?threadID=592611&start=0&tstart=0]
    but I can't seem to make this work using the GSS-API. I can successfully create a javax.security.auth.login.LoginContext.LoginContext and then call the login method on it to log in as a user. I then call the javax.security.auth.Subject.doAs() method which calls the run method in a class extending the javax.security.PrivilegedActionClass. But when I actually try to change the password using InitialDirContext.modifyAttributes(), I get the exception:
    *javax.naming.OperationNotSupportedException: [LDAP: error code 53 - 00002077: SvcErr: DSID-03190DC9, problem 5003 (WILL_NOT_PERFORM), data 0*
    *If anyone can help me figure out why it doesn't work, that would be great!*
    P.S: I know the error seems to suggest that there might be some active directory setting that is preventing this from working, but I've checked all relevant settings on the Windows 2003 server Active Directory that I can think of: In the User properties->Account->Account options, I've made sure the user can change password. Also, in the Group Policy->Computer Configuration->Windows Settings->Security Settings->Account Policies->Password Policy, Maximum password age is zero and so is minimum password age.
    Here's my java code:
    {code}import javax.naming.*;
    import javax.security.auth.*;
    import java.security.PrivilegedAction;
    import java.io.UnsupportedEncodingException;
    public void changeSecret((String uid, String oldPassword, String newPassword)
         throws NamingException, ACException{
    try {
         K5CallbackHandler cb = new K5CallbackHandler(uid, oldPassword);
         LoginContext lc = new LoginContext("marker", cb);
         lc.login();
         Subject.doAs(lc.getSubject(), new ChangePasswordAction(rz.getName(), oldPassword, newPassword));
         catch(LoginException e) {
         try {
              lc.logout();
         catch(LoginException e) {
    }ChangePasswordAction.java is:import javax.naming.*;
    import javax.naming.naming.directory.*;
    import java.io.UnsupportedEncodingException;
    private class ChangePasswordAction implements PrivilegedAction {
         private String uid;
         private String quotedOldPassword;
         private String quotedNewPassword;
         public ChangePasswordAction(String uid, String oldPassword, String newPassword) {
              this.uid = uid;
              quotedOldPassword = "\"" + oldPassword + "\"";
              quotedNewPassword = "\"" + newPassword + "\"";
         public Object run() {
              Hashtable env = new Hashtable(11);
              env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
              env.put(Context.PROVIDER_URL, "ldap://ad2k3:389");
              env.put(Context.SECURITY_AUTHENTICATION, "GSSAPI");
              try {
                   DirContext ctx = new InitialDirContext(env);
                   ModificationItem[] mods = new ModificationItem[2];
                   byte[] oldPasswordUnicode = quotedOldPassword.getBytes("UTF-16LE");
                   byte[] newPasswordUnicode = quotedNewPassword.getBytes("UTF-16LE");
                   mods[0] = new ModificationItem(DirContext.REMOVE_ATTRIBUTE, new BasicAttribute("unicodePwd", oldPasswordUnicode));
                   mods[1] = new ModificationItem(DirContext.ADD_ATTRIBUTE, new BasicAttribute("unicodePwd", newPasswordUnicode));
                   ctx.modifyAttributes(uid, mods);
                   ctx.close();
              } catch (NamingException e) {
              } catch (UnsupportedEncodingException e) {
              return null;
    }K5CallbackHandler is:import javax.security.auth.callback.*;
    final class K5CallbackHandler
    implements CallbackHandler {
         private final String name;
         private final char[] passwd;
         public K5CallbackHandler(String nm, String pw) {
              name = nm;
              if(pw == null) {
                   passwd = new char[0];
              else {
                   passwd = pw.toCharArray();
         public void handle(Callback[] callbacks)
         throws java.io.IOException, UnsupportedCallbackException {
              for(int i = 0; i < callbacks.length; i++) {
                   if(callbacks[i] instanceof NameCallback) {
                        NameCallback cb = (NameCallback) callbacks;
                        cb.setName(name);
                   else {
                        if(callbacks[i] instanceof PasswordCallback) {
                             PasswordCallback cb = (PasswordCallback) callbacks[i];
                             cb.setPassword(passwd);
                        else {
                             throw new UnsupportedCallbackException(callbacks[i]);
    }The relevant entry in the JAAS.conf file that is referred to as "marker" in the LoginContext constructor is:
    marker {
    com.sun.security.auth.module.Krb5LoginModule required client=TRUE;

    This is one of the two Active Directory operations I have never solved using Java/JNDI. (FYI the other one is Cross Domain Move).
    My gut feel is that the underlying problem (which happens to be common to both Change Password & X-Domain Move) is that Java/JNDI/GSSAPI does not negotiate a sufficiently strong key length that allows Active Directory to change passwords or perform cross domain moves when using Kerberos & GSSAPI.
    Active Directory requires at a minimum, 128 bit key lengths for these security related operations.
    In more recent Kerberos suites and Java versions, support for RC4-HMAC & AES has been introduced, so it may be possible that you can negotiate a suitably string key length.
    Make sure that your Kerberos configuration is using either RC4-HMAC or AES and that Java is requesting a strong level of protection. (You can do this by adding //Specify the quality of protection
    //Eg. auth-conf; confidentiality, auth-int; integrity
    //confidentiality is required to set a password
    env.put("javax.security.sasl.qop","auth-conf");
    //require high strength 128 bit crypto
    env.put("javax.security.sasl.strength","high"); in your ChangePasswordAction class.
    You may also want to enable sasl logging in your app to see what exactly is going on and you may also want to check on the Java Security forum how to configure/enforce/check both RC4-HMAC or AES is used as the Kerbeos cipher suite and that a string key length is being used.
    Good luck.

  • Use Profile Manager to configure 802.1x authentication to Active Directory

    I have an OS X Lion Server running profile manager, and I want to authenticate Macs against Active Directory. My test machine is running Lion as well.
    If I configure the profile to for WPA/WPA2 Enterprise security type and PEAP protocol with a generic user name and password with explicit access on the RADIUS server, the machine can get on the 802.1x network
    If I configure the profile to "Use as a Login Window configuration", the machine can get on the 802.1x network after entering the user name and password of an authorized RADIUS user.
    Here's my problem:
    I want to enable authentication for machines that are members of the Active Directory domain, but when I use the "Use Directory Authentication" option to authenticate with the target machine's directory credentials, the machine does not connect to my 802.1x network.
    Any thoughts?
    Thanks!!!!

    I'm trying to do the same thing, but I'm using Mountain Lion Profile Manager.  If I can't get this to work I'm going to try SCEP and certificate authentication.

  • Kerberos authentication with Active Directory

    I have tried using JAAS to authenticate to MS Active Directory and keep getting "javax.security.auth.login.LoginException: Pre-Authentication Information was invalid"
    I have tried authenticating with multiple user accounts and on three different realms (Active Directory domains).
    How do I need to format the username? I know that when using JNDI to access Active Directory I have to use the format "[email protected]" or the RDN. I have tried it both ways with JAAS kerberos authentication as well as with just the username by itself. I don't think that the username format is the problem though because if I set the account lockout policy to 5 failed attempts, sure enough my account will be locked out after running my code 5 times. If I give a username that doesn't exist in Active Directory I get the error "javax.security.auth.login.loginexception: Client not found in Kerberos database" Is there something special that I have to do to the password?
    I know that there is just something stupid that I'm missing. Here is the simplest example of code that I'm working with:
    import java.io.*;
    import javax.security.auth.callback.*;
    import javax.security.auth.login.*;
    import javax.security.auth.Subject;
    import com.sun.security.auth.callback.TextCallbackHandler;
    public class krb5ADLogin1 {
    public static void main(String[] args){
    LoginContext lc = null;
    try {
    lc=new LoginContext("krb5ADLogin1", new TextCallbackHandler());
    lc.login();
    catch(Exception e){
    e.printStackTrace();
    Here is my config file:
    krb5ADLogin1 {
    com.sun.security.auth.module.Krb5LoginModule required;
    The command I use to start the program is:
    java -Djava.security.krb5.realm=mydomain.com
    -Djava.security.krb5.kdc=DomainController.mydomain.com
    -Djava.security.auth.login.config=sample.conf krb5ADLogin1

    Hi there ... the Sun web site has the following snippet:
    http://java.sun.com/j2se/1.4/docs/guide/security/jgss/tutorials/Troubleshooting.html
    + javax.security.auth.login.LoginException: KrbException::
    Pre-authentication information was invalid (24) - Preauthentication failed
    Cause 1: The password entered is incorrect.
    Solution 1: Verify the password.
    Cause 2: If you are using the keytab to get the key (e.g., by
    setting the useKeyTab option to true in the Krb5LoginModule entry
    in the JAAS login configuration file), then the key might have
    changed since you updated the keytab.
    Solution 2: Consult your Kerberos documentation to generate a new
    keytab and use that keytab.
    Cause 3: Clock skew - If the time on the KDC and on the client
    differ significanlty (typically 5 minutes), this error can be
    returned.
    Solution 3: Synchronize the clocks (or have a system administrator
    do so).
    Good luck,
    -Derek

Maybe you are looking for

  • Deleting songs from library not deleting from hard drive

    I've read some other people with this problem, and haven't found a good answer. I had iTunes on my old XP computer, and when I would delete a song from my iTunes library it would give me the option to also send the actual file on my HD to the recycle

  • Like returns rows which do not macht if using NLS_SORT='BINARY_AI'

    Hi, I have a table with a nvarchar column in Oracle Xe 11. Using a select with like rows are returned which do not match the like condition. E.g. 'CR_abc' LIKE 'CR,%' is true for NLS_SORT=BINARY_AI. For GERMAN_AI the condition is false! Example to re

  • Some of the camera photos missing geotagging

    I,m using iPhone 4 with iOS5.... the gps location is ON for the camera, but some of the photos taken withthe camera are missing the geotagging. Cant find a pattern or a reason for it.few photos has the geo tagging and suddenly few images are without

  • UME in EP6.0

    hi experts i was trying to 3.5.3     Define a SAP R/3 System as a User Management Data Source i added the SAP R/3 system and tested the connection which was successfull but then it asked me to restart the application server when i started it again th

  • Large number of favorites (maps 3)

    Hi  I figured out how to converta large number of POIs (~2000) to an lmx file and import into maps. So far so good. Today I tried the ovi maps web browser application and the synchronize feature. It turned out that with this number of favorites ovi m