views:

508

answers:

4

Hi all, I have a small application with 3-4 servlets and a basic module that provide me authentication like:

public class Authentication {
    public boolean isUserAuthenticated(){
     ....
    }
}

Is there a way to check the authentication using my class BEFORE every other servlet calls, without have to add code in each of them? I'd like to avoid the check of the user for every servlet I have and for every servlet I will have to add.

Any suggestion is well accepted :)

Thanks, Roberto

+2  A: 

Absolutely, use a servlet filter. It's the standard way of implementing security in Java Web applications.

The Java Servlet specification version 2.3 introduces a new component type, called a filter. A filter dynamically intercepts requests and responses to transform or use the information contained in the requests or responses. Filters typically do not themselves create responses, but instead provide universal functions that can be "attached" to any type of servlet or JSP page.

cletus
+1  A: 

You can put your authentication logic in a Servlet Filter. If the filter finds a request not authenticated, it can redirect the user to a login page (or whatever).

Anything that gets to a servlet is implicitly authenticated by then.

Will Hartung
A: 

Use Acegi Security (now Spring Security). Using Spring will also make your life easier in other ways. (Spring security works using a servlet filter as mentioned in above posts).

LES2
Might be a bit heavy weight for his application requirements.
Paul Whelan
But I thought Spring was a "lightweight" container? ;)
LES2
A: 

Here's an open source library, http://spnego.sourceforge.net, that also uses a servlet filter.

The librrary supports integrated windows authentication/sso.

Pat Gonzalez