redirect user to login if not logged in

Hi,

I know there are allready lots of topics on this subject but I can't seem to understand the solutions yet.

So basically what I want to prevent is that users can just type in the url of the admin page (admin.jsp) in their browser and thereby skipping the login page (index.jsp)

Can someone give me a simple solution for this?

Would be great thanks!

[383 byte] By [eLIXa] at [2007-11-27 11:02:52]
# 1

Implement a Filter.

Pseudocode:doFilter(request, response, chain) {

if (user is not logged in && current page is not loginpage) {

response.sendRedirect("loginpage.jsp"); // Redirect to loginpage.

} else {

chain.doFilter(request, response); // Continue.

}

}

Googling for "userfilter", "loginfilter", "usersessionfilter", etc may deliver lot of useful results.

BalusCa at 2007-7-29 12:46:05 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 2

Ok so I googled and found your forum Balus :)

So this is what I found:

package mypackage;

import java.io.IOException;

import javax.servlet.Filter;

import javax.servlet.FilterChain;

import javax.servlet.FilterConfig;

import javax.servlet.HttpServletRequest;

import javax.servlet.HttpServletResponse;

import javax.servlet.ServletException;

import javax.servlet.ServletRequest;

import javax.servlet.ServletResponse;

public class LoginFilter implements Filter {

private FilterConfig filterConfig;

public void init(FilterConfig config) throws ServletException {

this.filterConfig = config;

}

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)

throws IOException, ServletException

{

HttpServletRequest httpRequest = (HttpServletRequest) request;

User user = (User) httpRequest.getSession().getAttribute("user"); // Get User from session.

String requestURI = httpRequest.getRequestURI(); // Get requested page.

if (user == null && !requestURI.contains("/login.jsf")) {

// No user found and not in login page yet, forward to login page.

((HttpServletResponse) response).sendRedirect("login.jsf");

return; // Abort the filter.

}

// User is found or we are already in the login page, continue filtering.

chain.doFilter(request, response);

}

public void destroy() {

this.filterConfig = null;

}

}

But when I do this I get errors on these lines:

import javax.servlet.HttpServletRequest;

import javax.servlet.HttpServletResponse;

that he couldn't import these.

Is there something I'm missing here?

eLIXa at 2007-7-29 12:46:05 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 3

Are you using an IDE? If so, which? If not, how are you compiling the code?

BalusCa at 2007-7-29 12:46:05 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 4

Yes I'm using NetBeans IDE 5.5

eLIXa at 2007-7-29 12:46:05 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 5

I don't know how to do it in Netbeans (I use Eclipse and I could explain it if you was using Eclipse), but you need to make sure that the javax.servlet API is available in the classpath of the JRE. Lookup for the servlet.jar file in the applicationserver's /lib directory and add it to the classpath of the JRE used in your IDE. The javaee.jar file from the JavaEE SDK is also sufficient.

BalusCa at 2007-7-29 12:46:05 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 6

Ok so I fixed it now. I guess... :p

But now my question is:

you have the following code:

User user = (User) httpRequest.getSession().getAttribute("user"); // Get User from session.

Now I guess you'll have to set that Attribute "user" somewhere? And how?

Sorry of these are total newbie questions. But that's just what I am at jsf... :p

eLIXa at 2007-7-29 12:46:05 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 7

The 'User' object just represents the logged in user.

In your login code you should put the User object as attribute in the HttpSession (and you should remove it in your logout code).

BalusCa at 2007-7-29 12:46:05 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 8

Time to show the code :p

Servlet LoginFilter.java:

package mct.data.beans;

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

/**

*

* @author Peter

* @version

*/

public class LoginFilter implements Filter {

private FilterConfig filterConfig;

public void init(FilterConfig config) throws ServletException {

this.filterConfig = config;

}

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)

throws IOException, ServletException

{

HttpServletRequest httpRequest = (HttpServletRequest) request;

Gebruiker user = (Gebruiker) httpRequest.getSession().getAttribute("user"); // Get User from session.

String requestURI = httpRequest.getRequestURI(); // Get requested page.

if (user == null && !requestURI.contains("/index.jsp")) {

// No user found and not in login page yet, forward to login page.

((HttpServletResponse) response).sendRedirect("index.jsp");

return; // Abort the filter.

}

// User is found or we are already in the login page, continue filtering.

chain.doFilter(request, response);

}

public void destroy() {

this.filterConfig = null;

}

}

login code (wich is in GebruikerMBean.java):

package mct.data.mbeans;

import mct.data.beans.Gebruiker;

import mct.db.dao.*;

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

/**

*

* @author Peter

*/

public class GebruikerMBean {

private Gebruiker newGebruiker;

private String username;

private String password;

public GebruikerMBean() {

System.out.println("GEBRUIKERMBEAN");

this.setNewGebruiker(new Gebruiker());

}

public String checkLogin() {

System.out.println(" BEGIN CHECK LOGIN -");

System.out.println("USERNAME: " + this.getNewGebruiker().getUsername());

System.out.println("PASSWORD: " + this.getNewGebruiker().getPassword());

System.out.println(" END CHECK LOGIN -");

EnqueteDAO dao = new EnqueteDAO("root","mypass","jdbc:mysql://localhost/enquete");

String userCorrect = dao.checkUsernamePassword(this.getNewGebruiker().getUsername(), this.getNewGebruiker().getPassword());

if(userCorrect == "userCorrect"){

System.out.println("-- BEGIN LOGIN --");

System.out.println("username: " + this.getNewGebruiker().getUsername());

System.out.println("password: " + this.getNewGebruiker().getPassword());

System.out.println("-- END LOGIN --");

return "loginCorrect";

Gebruiker user = (Gebruiker) httpRequest.getSession().setAttribute("user"); // Set User from session.

}

else{

System.out.println("-- LOGIN FAILED --");

return "loginIncorrect";

}

}

GETTERS & SETTERS

}

Is this what you mean then?

But now I get an error in my checkLogin method that he couldn't find the variable httpRequest. Altough I imported the javax.servlet files

Message was edited by:

eLIX

eLIXa at 2007-7-29 12:46:05 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 9

When you are within a JSF action you can get access to the session via FacesContext.getCurrentInstance().getExternalContext().getSessionMap(). I.e., you do not need the HttpServeltRequest object.

Also, I noticed you put the code to place the user in the session after the return statement.

RaymondDeCampoa at 2007-7-29 12:46:05 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 10

Ok again I'm a little bit closer I think.

I changed the line into:

Gebruiker user = (Gebruiker) httpRequest.getSession().setAttribute("user", user); // Set User from session.

But I still get an error: inconvertible types found: void required: mct.data.beans.Gebruiker

Message was edited by:

eLIX

eLIXa at 2007-7-29 12:46:05 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 11

I'm still in the dark here.

Any help would be appreciated.

What I've tried allready:

public String checkLogin() {

HttpServletRequest request;

System.out.println(" BEGIN CHECK LOGIN -");

System.out.println("USERNAME: " + this.getNewGebruiker().getUsername());

System.out.println("PASSWORD: " + this.getNewGebruiker().getPassword());

System.out.println(" END CHECK LOGIN -");

EnqueteDAO dao = new EnqueteDAO("root","221085pd","jdbc:mysql://localhost/enquete");

String userCorrect = dao.checkUsernamePassword(this.getNewGebruiker().getUsername(), this.getNewGebruiker().getPassword());

HttpServletRequest httpRequest = (HttpServletRequest) request;

if(userCorrect == "userCorrect"){

System.out.println("-- BEGIN LOGIN --");

System.out.println("username: " + this.getNewGebruiker().getUsername());

System.out.println("password: " + this.getNewGebruiker().getPassword());

System.out.println("-- END LOGIN --");

Gebruiker user = (Gebruiker) httpRequest.getSession().setAttribute("user", user); // Set User from session.

return "loginCorrect";

}

else{

System.out.println("-- LOGIN FAILED --");

return "loginIncorrect";

}

}

Error: inconvertible types

found: void

required: mct.data.beans.Gebruiker

And 2nd:

public String checkLogin() {

FacesContext facesContext;

System.out.println(" BEGIN CHECK LOGIN -");

System.out.println("USERNAME: " + this.getNewGebruiker().getUsername());

System.out.println("PASSWORD: " + this.getNewGebruiker().getPassword());

System.out.println(" END CHECK LOGIN -");

EnqueteDAO dao = new EnqueteDAO("root","221085pd","jdbc:mysql://localhost/enquete");

String userCorrect = dao.checkUsernamePassword(this.getNewGebruiker().getUsername(), this.getNewGebruiker().getPassword());

if(userCorrect == "userCorrect"){

System.out.println("-- BEGIN LOGIN --");

System.out.println("username: " + this.getNewGebruiker().getUsername());

System.out.println("password: " + this.getNewGebruiker().getPassword());

System.out.println("-- END LOGIN --");

Gebruiker user = (Gebruiker) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().setAttribute("user", user); // Set User from session.

return "loginCorrect";

}

else{

System.out.println("-- LOGIN FAILED --");

return "loginIncorrect";

}

}

Error: cannot find symbol

method setAttribute(...)

location(...)

eLIXa at 2007-7-29 12:46:05 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 12

The error in your second batch of code is that you are treating the return value of getSessionMap() as if it were an instance of HttpSession. It is not. Look up the method in the javadoc and see what it does return.

RaymondDeCampoa at 2007-7-29 12:46:05 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...