How to check user password in ldap whith java with given LdapContext?

前端 未结 4 882
攒了一身酷
攒了一身酷 2020-12-08 15:58

I do have a web-application, where users must log in. The password is stored in a LDAP server. All information about the LDAP server are stored in the application server (gl

4条回答
  •  佛祖请我去吃肉
    2020-12-08 16:28

    i have done same in my application. following is the which might be useful to you.

        package com.agileinfotech.bsviewer.servlet;
    
        import java.io.IOException;
        import javax.servlet.RequestDispatcher;
        import javax.servlet.ServletException;
        import javax.servlet.http.HttpServletRequest;
        import javax.servlet.http.HttpServletResponse;
        import javax.naming.*;
        import javax.naming.directory.*;
        import java.util.Hashtable;
    
        public class Login extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
    
        public Login() {
        super();
        }
    
        protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
        final String SUCCESS = "loin.jsp";
        final String FAILURE = "Failure.html";
        String strUrl = "login.html";
        String username = request.getParameter("username");
        String password = request.getParameter("password");
    
    
    
        Hashtable env = new Hashtable(11);
    
        boolean b = false;
    
        env.put(Context.INITIAL_CONTEXT_FACTORY,
        "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, "ldap://localhost:10389");
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, "uid="+ username +",ou=system");
        env.put(Context.SECURITY_CREDENTIALS, password);
    
        try {
        // Create initial context
        DirContext ctx = new InitialDirContext(env);
    
        // Close the context when we're done
        b = true;
        ctx.close();
    
        } catch (NamingException e) {
        b = false;
        }finally{
        if(b){
        System.out.print("Success");
        strUrl = SUCCESS;
        }else{
        System.out.print("Failure");
        strUrl = FAILURE;
        }
        }
        RequestDispatcher rd = request.getRequestDispatcher(strUrl);
        rd.forward(request, response);
    
        }
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        processRequest(request,response);
        }
    
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        processRequest(request,response);
        } 
        }
    

提交回复
热议问题