Problem getting session information


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 3 of 3

Thread: Problem getting session information

  1. #1
    Join Date
    Mar 2006
    Posts
    100

    Problem getting session information

    Ok so the idea is simple enough, handle logins using serverside auth and then if auth then set a session variable to keep track of the user. Once the user decides to logout the session is destroyed. Problem is it doesn't apear to be working.
    Problems
    1.) The login feature seems to work and the userName session variable can be accessed through a xmlhttprequest to the server, however, when I try to just run the servlet directly I get a blank string. How can the session be retrieved fine by the request but another IE window sees nothing.

    2.) Session.invalidate does not cause the session variable to be destroyed.

    here are some code snipets
    Code:
    //Client Side
    
    function login()
    {
        userName="";
        xmlUserName=GetXmlHttpObject();
        if (xmlUserName == null)
        {
            alert ("Your browser does not support the XMLHttpRequest object. Please upgrade to a newer browser.");
            return;
        }
        queryString="mode=getValue&varName=userName";
        //xmlUserName.onreadystatechange=responseUN;
        xmlUserName.open("POST",urlSession,false);
        xmlUserName.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        xmlUserName.send(queryString);
    //    if (xmlUserName.status=="PAGE_SUCCESS")
    //    { 
        
        userName=xmlUserName.responseText;
        alert(xmlUserName.status);
        alert(xmlUserName.responseText);
        if (userName != "")
        {
            //userName.replace(" ","*");
            //alert(userName);
            getCurrentPage();
        }
        else
        {
            alert("Please Log In");
            window.location = "***.htm";
        }
    
        
    }
    
    
    
    //responseText is false
    function logout()
    {
        alert("we're in");
        userName="";
        xmlUserName=GetXmlHttpObject();
        if (xmlUserName == null)
        {
            alert ("Your browser does not support the XMLHttpRequest object. Please upgrade to a newer browser.");
            return;
        }
        var url="http://*******/LdapAuthServlet";
        queryString="mode=logout";
        //xmlUserName.onreadystatechange=responseUN;
        xmlUserName.open("POST",urlSession,false);
        xmlUserName.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
        xmlUserName.send(queryString);
    //    if (xmlUserName.status=="PAGE_SUCCESS")
    //    { 
        
        //userName=xmlUserName.responseText;
        alert(xmlUserName.status);
        alert(xmlUserName.responseText);
    //    if (userName != "")
    //    {
    //        //userName.replace(" ","*");
    //        //alert(userName);
    //        getCurrentPage();
    //    }
    //    else
    //    {
            alert("Please Log In");
            window.location = "****.htm";
        //}
    
        
    }
    
    //server side
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException
    	{
    		PrintWriter writer = null;
    		setVar();
    
    		try
    		{
    			writer = response.getWriter();
    			//Setup Variables
    		
    			boolean validLogin = false;
    			//get the mode to accomplish    
    			String mode = request.getParameter("mode");
    			String falsePos = request.getParameter("falsePos");
    			// got hold of the user session
    			HttpSession session = request.getSession(true);
    			// retrieving session info
    
    
    							if (!(mode == null))
    				{
    					if (mode.equals("login"))
    					{
    						String userName = request.getParameter("userName");
    						String passWord = request.getParameter("passWord");
    						//Make sure the variables were included
    						if ((!(userName == null)) && (!(passWord == null)))
    						{
    							//Check the username/Password with LDAP
    							validLogin = checkAuth(userName, passWord);
    
    							//Handle The Result
    							if (validLogin)
    							{
    								boolean changed = sessionEditor.changeSessionVariable("userName", userName, session);
    								if (changed)
    								{
    									writer.write("success:login");
    								}
    								else
    								{
    									writer.write("failed:Could not set session variable");
    								}
    							}	
    							else
    							{
    								boolean changed = sessionEditor.changeSessionVariable("userName", null, session);
    								writer.write("failed:Bad Username/ID");
    							}
    						}
    					}
    
    					if (mode.equalsIgnoreCase("logout"))
    					{
    						if (session != null)
    						{
    							boolean changed = sessionEditor.changeSessionVariable("userName",null, session);
    							errLog.writeAlert("Session variable changed:" + changed);
    							if (changed)
    							{
    								changed = sessionEditor.endSession(session);
    								errLog.writeAlert("Session Deleted:" + changed);
    								if (changed)
    								{
    									writer.write("success:logout");
    									errLog.writeAlert("success:logout");
    								}
    								else
    								{
    									writer.write("failed:No Session to invalidate in the session function");
    									errLog.writeAlert("failed:No Session to invalidate in the session function");
    								}
    							}
    							else
    							{
    								writer.write("failed:to set the session variable");
    								errLog.writeAlert("failed:to set the session variable");
    							}
    						}
    						else
    						{
    							writer.write("failed:No Session to invalidate");
    							errLog.writeAlert("failed:No Session to invalidate");
    						}
    						
    					}
    
    				}
    			
    		}
    		catch (Exception ex) 
    		{
    			try
    			{
    				writer = response.getWriter();
    				writer.write("Error:");
    				ex.printStackTrace(writer);
    				errLog.writeError(ex);
    			}
    			catch (Exception e) { }
    		}
    		finally
    		{
    			writer.flush();
    		}
    		
    	}
    
    public boolean changeSessionVariable(String varName, String varValue, HttpSession session)
    	{
    		if (session != null)
    		{
    			try
    			{
    
    				//if (varName != "userName")
    				//{
    					session.setAttribute(varName, varValue);
    					return (true);
    				//}
    				//else
    				//{
    				//    errLog.writeAlert("Username not found");
    				//    return (false);
    				//}
    			}
    			catch (Exception ex)
    			{
    				errLog.writeError(ex);
    				return (false);
    			}
    		}
    		else
    		{
    			errLog.writeAlert("No Session found, This was supposed to be a parameter so please check the code calling this function");
    			return (false);
    		}
    	}
    public boolean endSession(HttpSession session)
    	{
    		try
    		{
    			session.invalidate();
    			return true;
    		}
    		catch(Exception ex)
    		{
    			errLog.writeError(ex);
    			return false;
    		}
    	}

  2. #2
    Join Date
    Feb 2007
    Posts
    1

    Exclamation

    Have you received a solution to your problem? We have suddenly started experiencing this exact same problem with some of our users.

    Anyone else have any ideas?

    Thanks, Schalk!

  3. #3
    Join Date
    Mar 2006
    Posts
    100
    Not sure what helped it but here is my new code
    Code:
    /* ***************************************************
    *Author: Jackie Gleason 
    *Company: Dayhuff Group
    *Desc: This servlet is used to authenticate with an
    *IBM Domino Database
    ******************************************************/
    import HDOE.*;
    
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.*;
    
    import java.util.Date;
    import java.io.*;
    import java.util.*;
    
    import javax.naming.*;
    import javax.naming.ldap.*;
    import javax.naming.directory.*;
    import java.util.Hashtable;
    import java.net.*;
    
    public class LdapAuthServlet extends HttpServlet
    {
    	errorLog er = new errorLog();
    	String org = "";
    	String ldap = "";
    	private void setVar()
    	{
    		configProps configInfo = new configProps();
    		org = configInfo.getOrganization();
    		ldap = configInfo.getLdap();
    	}
    	
    	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException
    	{
    		setVar();
    		PrintWriter writer = null;
    		try
    		{
    			writer = response.getWriter();
    			HttpSession session = request.getSession(true);
    			//get the mode. The mode tells the servlet what to do
    			String mode = request.getParameter("mode");
    			if (mode != null)
    			{
    				if (mode.equalsIgnoreCase("login"))
    				{
    					String userName = request.getParameter("userName");
    					String passWord = request.getParameter("passWord");
    					
    					if (!(passWord.equals("")||passWord.equals(" ")||passWord.equals(null))) userLogIn(writer, userName, passWord, session);
    					else writer.println("Fail:Invalid Username and password");
    				}
    				else if (mode.equalsIgnoreCase("getUserName"))
    				{
    					String att = (String)session.getAttribute("userName");
    					if (att.equals(null)) att = "";
    					if (att.equals("null")) att = "2";
    					if (att.equals("")) att = "3";
    					writer.println(att);
    				}
    				else if (mode.equalsIgnoreCase("logout"))
    				{
    					session.invalidate();
    					String att = (String)session.getAttribute("userName");
    					if (att.equals(null)) att="1";
    					if (att.equals("null")) att="2";
    					if (att.equals("")) att="3";
    					writer.println(att);
    				}
    			}
    		}
    		catch (Exception ex)
    		{
    			er.writeError(ex);
    		}
    
    
    	}
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException
    {
    	doGet(request, response);
    }
    
    public boolean checkAuth(String UserName, String passWord)
    {
    	try
    	{
    
    		String dn = "";
    		//This function authenticates a user with LDAP
    		// Set up environment for creating initial context
    		Hashtable authEnv = new Hashtable(11);
    		if (org != "" && org != null)
    		{
    			String base = "o=" + org;
    			dn = "cn=" + UserName + "," + base;
    		}
    		else
    		{
    			dn = "cn=" + UserName;
    		}
    		//writeToLog("dn:"+dn+" ldap:"+ldap+" password:"+passWord);
    		authEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    		authEnv.put(Context.PROVIDER_URL, ldap);
    		authEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
    		authEnv.put(Context.SECURITY_PRINCIPAL, dn);
    		authEnv.put(Context.SECURITY_CREDENTIALS, passWord);
    
    		DirContext authContext = new InitialDirContext(authEnv);
    		return true;
    	}
    	catch (AuthenticationException authEx)
    	{
    		er.writeError(authEx);
    		return false;
    	}
    	catch (NamingException namEx)
    	{
    		er.writeError(namEx);
    		return false;
    	}
    	catch (Exception ex)
    	{
    		er.writeError(ex);
    		return false;
    	}
    }
    
    public void userLogIn(PrintWriter writer, String userName, String passWord,HttpSession session)
    {
    	try
    	{
    		
    		boolean validLogin = checkAuth(userName, passWord);
    		if (validLogin)
    		{
    			
    			session.setAttribute("userName", userName);
    			String att = (String)session.getAttribute("userName");
    			writer.println("Success:Logged In:" + att);
    		}
    		else
    		{
    		
    			writer.println("Fail:Invalid Username and password");
    				
    		}
    	}
    	catch (Exception ex) 
    	{
    			//writer = response.getWriter();
    			//writer.println("Fail:Error check log");
    			
    		er.writeError(ex);
    	}
    	finally
    	{
    		writer.flush();
    		writer.close();
    	}
    }
    }

Similar Threads

  1. Replies: 1
    Last Post: 07-12-2006, 12:16 PM
  2. Reliability Problem
    By elise in forum .NET
    Replies: 0
    Last Post: 10-30-2002, 04:39 AM
  3. Problem with Session variables and Cookies
    By Bragi Fannar in forum ASP.NET
    Replies: 0
    Last Post: 02-20-2002, 08:28 AM
  4. Replies: 1
    Last Post: 01-19-2002, 02:09 PM
  5. SV: Stoping someone from accessing a page directly
    By Gunnar Syren in forum ASP.NET
    Replies: 5
    Last Post: 10-26-2000, 10:25 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center