Kimi's NutShell

我荒废的今日,正是昨日殒身之人祈求的明日

BlogJava 新随笔 管理
  141 Posts :: 0 Stories :: 75 Comments :: 0 Trackbacks

/*
 * @author  Kemi *
 *
 * Creation/Modification History  :
 *
 * 10-May-2006   created
 *
 */

package com.daphne.security.ldap;

import com.daphne.security.ldap.LdapParameters;
import java.util.Hashtable;
import java.util.logging.Logger;
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;


/**
 * This class manages all Directory operations.
 */
public class DirectoryManager {

    private static DirContext dirctx = null;
    private static final Logger logger =
        Logger.getLogger(DirectoryManager.class.getName());
    private static final String dir = "cn=orcladmin,cn=users,";

    /**
   * Empty default Constructor.
   */
    public DirectoryManager() {
    }

    /**
   * Checks if the specified uname is a member of the specified group.
   *
   * @param uname  Relative Distinguished name of the user
   * @param groupname Distingushed name of the group
   * @return  true - if the user belongs to the group, else false
   * @exception NamingException if any directory operation fails
   */
    public static boolean isUserInGroup(String uname,
                                 String groupname) throws NamingException {

        boolean ingroup = false;

        // Get the Distinguished Name of the user
        String userDN = getUserDN(uname);
        String groupDN = getGroupDN(groupname);
        if(userDN==null || groupDN==null){
            return false;
        }

        // Filter to check if the user DN is a member
        // A user is a member of a group if the uniqueMember attribute of that group entry
        // has the user DN value.
        String filter = "(uniqueMember=" + userDN + ")";

        // Initialize search controls to search with scope as sub tree
        SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        // Set the attributes to be returned
       // searchControls.setReturningAttributes(new String[] { "cn" });

        // Search under the specified group
        if(dirctx==null){
            System.out.println("gerge");
        }
        NamingEnumeration results =
            dirctx.search(groupDN, filter, searchControls);

        // If the search has results, then the user is a member   
        if (results.hasMore()) {
            ingroup = true;
        }
        // else user not present, i.e defaulted

        return ingroup;
    }

    /**
   *  Authenticates the user credentials with Directory.
   *
   * @param username  User Name of the user
   * @param passwd Password of the user
   * @return  true - if the credentials are valid
   *
   * @exception AuthenticationException If credentials are invalid
   * @exception NamingException if any directory operation fails
   */
    public static boolean authenticateUser(String username,
                                    String passwd) throws AuthenticationException,
                                                          NamingException {

        boolean authorized = false;

        // Get the Distinguished Name
        String dn = getUserDN(username);
        if(dn==null){
            return false;
        }
     try {
                    // Authenticate with Directory
                    dirctx = getDirectoryContext(dn, passwd);
                    authorized = true;
       
                } catch (AuthenticationException authEx) {
       
                    //throw new AuthenticationException(" Invalid Password ");
                     logger.severe("Invalid Password ");
                }


        return authorized;
    }

    /**
   * Retrieves the Distinguished name of them of the specified RDN.
   *
   * @param uname  Relative Distinguished name.
   * @return  Distinguished name of the user
   * @exception NamingException if directory operation fails
   */
    public static String getUserDN(String uname) throws NamingException {

       // DirContext dCtx = null;
        System.out.println("ROOT:" + LdapParameters.getRootContext());
        System.out.println("User:" + LdapParameters.getUserContext());
        System.out.println("Group:" + LdapParameters.getGroupContext());
        System.out.println("RDN:" + LdapParameters.RDN);


        // if Grocery context is available, use it, else create one as application entity
        if (dirctx == null) {
            dirctx=
getDirectoryContext(dir + LdapParameters.getRootContext(), "123qweasd");
        }
        if (dirctx == null) {
            System.out.println("NULL DCTX");
        } else {
            System.out.println("Notnull DCTX");
        }

        SearchResult searchResult = null;
        NamingEnumeration results = null;
        String userDN = null;
        String filter = "(" + LdapParameters.RDN + "=" + uname + ")";

        // To set search controls to search with subtree scope
        SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

        // Search the directory based on the search string from the specified context
        try{
        results =
                dirctx.search(LdapParameters.getUserContext(), filter, searchControls);
        }catch(Exception e){
            logger.severe("Match Error:Invalid Username ");
        }

        // If matching record found
        if (results.hasMore()) {

            searchResult = (SearchResult)results.next();
            // Build the User DN
            userDN =
                    searchResult.getName() + "," + LdapParameters.getUserContext();

        } else {
            // User not found
            //throw new NamingException(" Invalid Username ");
            logger.severe("Invalid Username ");
        }

        return userDN;
    }

    public static String getGroupDN(String groupname) throws NamingException {

     
        if (dirctx == null) {
            dirctx =
getDirectoryContext(dir + LdapParameters.getRootContext(), "123qweasd");
        }
        if (dirctx == null) {
            System.out.println("NULL DCTX");
        } else {
            System.out.println("Notnull DCTX");
        }

        SearchResult searchResult = null;
        NamingEnumeration results = null;
        String groupDN = null;
        String filter = "(cn=" + groupname + ")";

     
        SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

     
     
        results =
                dirctx.search(LdapParameters.getGroupContext(), filter, searchControls);
      
          
      

        // If matching record found
        if (results.hasMore()) {

            searchResult = (SearchResult)results.next();
           
            groupDN =
                    searchResult.getName() + "," + LdapParameters.getGroupContext();

        } else {
       
            logger.severe("Invalid Groupname ");
        }

        return groupDN;
    }

    /**
   *  Initializes a Directory Context with the specified credentials and return it.
   *  If the password is blank(null), it binds as anonymous user and returns the
   *  context.
   *
   * @param username Directory user name
   * @param password Directory user password
   * @return  valid directory context, if credentials are valid
   * @exception AuthenticationException  if credentails are invalid
   * @exception NamingException if directory operation fails
   */
    public static DirContext getDirectoryContext(String username,
                                          String password) throws AuthenticationException,
                                                                  NamingException {

        DirContext dCtx = null;

        //Build the LDAP url
        String ldapurl =
            "ldap://" + LdapParameters.dirHostName + ":" + LdapParameters.dirPort;

        Hashtable env = new Hashtable();
        env.put(Context.INITIAL_CONTEXT_FACTORY,
                "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, ldapurl);

        // if password is specified, set the credentials
        if (password != null) {
            env.put(Context.SECURITY_AUTHENTICATION, "simple");
            env.put(Context.SECURITY_PRINCIPAL, username);
            env.put(Context.SECURITY_CREDENTIALS, password);
        }

        // Bind and initialize the Directory context
        dCtx = new InitialDirContext(env);

        return dCtx;
    }

//        public static void main(String[] args) {
//            DirectoryManager dm = new DirectoryManager();
//            try {
//        //            if (dm.isUserInGroup("kemi", "销售")) {
//        //                System.out.println("True:User in Group");
//        //
//        //            } else {
//        //                System.out.println("False:Wrong name or group");
//        //            }
//                if(dm.authenticateUser("kemi","123qweasd")){
//                    System.out.println("True:Password successful");
//                }else{
//                    System.out.println("False:Failed to match pw and name");
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }

    }


  

 

 

posted on 2006-05-10 14:32 Kimi 阅读(409) 评论(0)  编辑  收藏 所属分类: Java

只有注册用户登录后才能发表评论。


网站导航: