¿Como verificar si un usuario esta logeado en una web?

1,502 views
Skip to first unread message

Alejandro Schenk

unread,
Feb 15, 2006, 1:00:08 PM2/15/06
to jav...@googlegroups.com
Hola estaba viendo un poco JSP y me surgio una duda.
Tengo 3 paginas: login, menu y juegos. El problema es que el usuario si pone en la url http://../juegos.jsp, entra directamente.
Lo que quiero hacer es que si el usuario no esta logueado que lo redireccione a la pagina de login.
Buscando en internet encontre una persona que lo que hacia era ponerle a cada pagina un tag "<%@include file="header_login.jsp"%>"
incluye la pagina "header_login" que lo que hace es llamar a un custom-tag que se encarga de saber si el usuario esta logeado o no, en caso de que no este logueado lo redirecciona a la pagina de login.
Al principio me parecio buena idea, hasta que me di cuenta que tenia que poner ese tag en todas las *.jsp que quiero que verifique al usuario.
Mi pregunta es ¿hay alguna forma mas prolija? o sea derivar ese problema a otra servicio/servlet o como quieran llamarlo.
Gracias.

Jorge Ariel Damian Kagiagian

unread,
Feb 15, 2006, 1:08:45 PM2/15/06
to jav...@googlegroups.com

Mira… lo malo de usar ese redirect es que vas a programar como si fuera php.

Deberias implementar el patron filter Caín.

 

Saludos

 


Alejandro Narancio

unread,
Feb 15, 2006, 1:07:46 PM2/15/06
to jav...@googlegroups.com
Lo mejor es poner un listener a nivel de aplicación, entonces apenas se emite un requerimiento te fijas si el usuario esta logueado, si no esta logueado lo redirigis a la pagina de login y si esta logueado lo dejas pasar.
Esa es la mejor forma porque pones toda la logica en un solo lado y no ensucias las JSPs con esa validación.

Saludos,

Alejandro

Jorge Ariel Damian Kagiagian

unread,
Feb 15, 2006, 1:18:28 PM2/15/06
to jav...@googlegroups.com

CORRIJO

FILTER CHAIN

Se configura el web.xml en el cual filtras los accesos a traves de una clase java que implementa Filter

Ejemplo

 

package ar.com.supergol.jsg.core.filterChain;

 

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

 

import ar.com.kevor.core.bean.usuario.Usuario;

 

public class UsuarioSessionFilter implements Filter {

 

    private ServletContext context = null;

 

    public void init(FilterConfig config) throws ServletException {

        this.context = config.getServletContext();

    }

 

    public void destroy() {

    }

 

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

                        throws IOException, ServletException {

 

                String nome = "";

 

                if (request instanceof HttpServletRequest) {

                    nome = ((HttpServletRequest)request).getRequestURI();

                }

 

                if( !nome.contains("/jsg/admin/")){

                            Usuario usuario = (Usuario)((HttpServletRequest)request).getSession().getAttribute("usuario");

                           

                            if ( usuario == null){

                                    usuario = new Usuario();

                            }

           

                            if ( usuario.getId() == null ){

                                    if (

                                                   ( !nome.equals("/jsg/checkLogin.do"))

                                                           && ( !nome.equals("/jsg/login.do"))

                                                           && ( !nome.equals("/jsg/home.do"))

                                                           && ( !nome.equals("/jsg/reglamento.do"))

                                                           && ( !nome.equals("/jsg/popUpServicio.do"))

                                                           && ( !nome.equals("/jsg/comoSeJuega.do"))                                         

                                                           && ( !nome.equals("/newsletter/linkVisited.do"))

                                                           && ( !nome.equals("/newsletter/estadistica.do"))

                                                           && ( !nome.equals("/newsletter/verNewsLetter.do"))

                                                           && ( !nome.equals("/newsletter/verNewsLetterLink.do"))

                                                           && ( !nome.equals("/newsletter/verNewsLetterDetalle.do"))

                                                           && ( !nome.equals("/newsletter/listarClientes.do"))

                                                           && ( !nome.equals("/newsletter/listarClienteDepartamentos.do"))                                                

                                                           && ( !nome.equals("/newsletter/listarNewsLetters.do"))

                                                ){

                                                this.context.getRequestDispatcher("/usuarioExceptionHandler.do").forward(request,response);

                                    }else{

                                                chain.doFilter(request, response);

                                    }

                            }else{

                                                chain.doFilter(request, response);

                            }

                }else{

                        Usuario usuario = (Usuario)((HttpServletRequest)request).getSession().getAttribute("usuarioAdmin");

                            if ( usuario == null){

                                    usuario = new Usuario();

                            }

                           

                            if ( usuario.getId() == null ){

                                    if (

                                                   ( !nome.equals("/jsg/admin/checkLogin.do"))

                                                           && ( !nome.equals("/jsg/admin/login.do"))

                                                ){

                                                this.context.getRequestDispatcher("/admin/usuarioExceptionHandler.do").forward(request,response);

                                    }else{

                                                chain.doFilter(request, response);

                                    }

                            }else{

                                                chain.doFilter(request, response);

                            }

                }

               

    }   

}

 


Ernesto Tagwerker

unread,
Feb 15, 2006, 1:14:26 PM2/15/06
to jav...@googlegroups.com
Hola Alejandro,

Si, hay otras formas de hacerlo. La que estamos usando en el proyecto
que estoy trabajando ahora es la siguiente:

Cada request se valida en un servlet, si el usuario es valido y tiene
permisos para acceder al recurso se le envia la respuesta con la
pagina, si el usuario no es valido se le muestra la pagina de login y
se guarda el url pedido (para poder redirigirlo una vez que se loguee)

Para validar un pedido nos fijamos si el pedido tiene una sesion
valida asociada. Una vez que se autentica usuario/password se crea una
sesión.

Espero que sirva de algo.

Saludos.
Ernesto.


On 2/15/06, Alejandro Schenk <ale.s...@gmail.com> wrote:

Alejandro Schenk

unread,
Feb 15, 2006, 1:17:42 PM2/15/06
to jav...@googlegroups.com
Tenes mas informacion ?? porque estuve buscando en google y no encontre mucho.
Gracias. !!!

El día 15/02/06, Jorge Ariel Damian Kagiagian < jadkag...@supergol.com> escribió:

Mira… lo malo de usar ese redirect es que vas a programar como si fuera php.

Deberias implementar el patron filter Caín.

 

Saludos

 


De: jav...@googlegroups.com [mailto: jav...@googlegroups.com] En nombre de Alejandro Schenk
Enviado el: miércoles, 15 de febrero de 2006 15:00
Para: jav...@googlegroups.com
Asunto: [JavaSOS] ¿Como verificar si un usuario esta logeado en una web?

 

Hola estaba viendo un poco JSP y me surgio una duda.

Tengo 3 paginas: login, menu y juegos. El problema es que el usuario si pone en la url http://../juegos.jsp , entra directamente.


Lo que quiero hacer es que si el usuario no esta logueado que lo redireccione a la pagina de login.
Buscando en internet encontre una persona que lo que hacia era ponerle a cada pagina un tag "<%@include file="header_login.jsp"%>"
incluye la pagina "header_login" que lo que hace es llamar a un custom-tag que se encarga de saber si el usuario esta logeado o no, en caso de que no este logueado lo redirecciona a la pagina de login.
Al principio me parecio buena idea, hasta que me di cuenta que tenia que poner ese tag en todas las *.jsp que quiero que verifique al usuario.
Mi pregunta es ¿hay alguna forma mas prolija? o sea derivar ese problema a otra servicio/servlet o como quieran llamarlo.

Gracias.


Alejandro Schenk

unread,
Feb 15, 2006, 1:22:10 PM2/15/06
to jav...@googlegroups.com
Si eso mismo estaba buscando, de hecho al principio lo pense de esa forma. Pero conozco dos listeners, Context y Session, ¿hay alguno que me permite hacer lo que decis??? Porque los dos se llaman cuado se crea y/o se cierra el WebContext o la Sesion.
Que Listener tengo que implementar??


El día 15/02/06, Alejandro Narancio <ale.na...@gmail.com > escribió:

Alejandro Schenk

unread,
Feb 15, 2006, 1:39:28 PM2/15/06
to jav...@googlegroups.com
Buscando por google encontre un pagina que habla de filtros y explica justamente lo que quiero hacer.
Aca les dejo la pagina:
http://www2.ing.puc.cl/~jnavon/IIC3582/Clases2005/13.%20Architecture.pdf
En la seccion de Filtros esta todo.


El día 15/02/06, Alejandro Schenk <ale.s...@gmail.com> escribió:

David Guzman

unread,
Feb 15, 2006, 1:21:28 PM2/15/06
to jav...@googlegroups.com
Estoy de acuerdo con Alejandro ;-)

ambas propuestas son buenas, pero acá hemos usado más la ke dice Alejandro :-D

Jorge Ariel Damian Kagiagian

unread,
Feb 15, 2006, 1:59:54 PM2/15/06
to jav...@googlegroups.com

listener a nivel de aplicación …. Filter Chain

 


De: jav...@googlegroups.com [mailto:jav...@googlegroups.com] En nombre de Alejandro Narancio


Enviado el: miércoles, 15 de febrero de 2006 15:08
Para: jav...@googlegroups.com

Alejandro Narancio

unread,
Feb 15, 2006, 2:10:51 PM2/15/06
to jav...@googlegroups.com
Si te interesa puedo ver de armarte un WAR con un ejemplo, te interesa?

saludos

On 2/15/06, Alejandro Schenk <ale.s...@gmail.com> wrote:

Jose Luis Mayorga Alcantara

unread,
Feb 15, 2006, 4:00:41 PM2/15/06
to jav...@googlegroups.com
Alejandro,

Si lo que te interesa es unicamente validar si el usuario tiene acceso
o no y configurar algunos roles, puedes usar la funcionalidad que ya
trae tu contenedor de servlets.

En el caso de Tomcat se llaman realms.

Saludos,

José Luis Mayorga A.

Alejandro Schenk

unread,
Feb 16, 2006, 8:28:43 AM2/16/06
to jav...@googlegroups.com
Estoy usando Jetty y la verdad que ni idea si se puede hacer filtros.
Alejandro si no tenes ninguna molestia en postear un ejemplo estuviese muy bueno.



El día 15/02/06, Jose Luis Mayorga Alcantara <jlma...@gmail.com> escribió:

Jose Luis Mayorga Alcantara

unread,
Feb 16, 2006, 10:01:14 AM2/16/06
to jav...@googlegroups.com
Alejandro,

Espero que la siguiente informacion te sirva, fue tomada de la
documentación de Jetty en la siguiente pagina:

http://jetty.mortbay.org/jetty/plus/

JAAS
JAAS provides a pluggable framework for authenticating and authorising
users. JettyPlus JAAS integrates this with the declarative security
model of the Java Servlet Specification.
The Jetty JAAS classes are not included in the main JettyPlus jar
(org.mortbay.jetty.plus.jar). Instead, it is built as
org.mortbay.jaas.jar to enable it to be used either with standard
Jetty, or with JettyPlus.

As JAAS is a pluggable framework, the Jetty JAAS integration aims to
dictate as little as possible whilst providing a sufficiently flexible
infrastructure to allow users to drop in their own custom
LoginModules. An example LoginModule
(org.mortbay.jaas.spi.JDBCLoginModule), interacting with a database to
store user names, passwords and roles, is included with the release to
illustrate what to implement.

Some important classes are:

org.mortbay.jaas.JAASUserRealm
This bridges Jetty's realm concept to JAAS. This class must be
configured as the realm for your webapp.
org.mortbay.jaas.JAASPrincipal
Implements the java.security.Principal interface. This class is used
by the sample JDBCLoginModule, but the Jetty JAAS infrastructure is
Principal agnostic, meaning you can use your own implementation of
this class for your LoginModules if you wish.
org.mortbay.jaas.JAASRole
This is a Principal that represents a role possessed by a user.
org.mortbay.jaas.JAASGroup
An implementation of the java.security.acl.Group interface. It is used
only by the sample JDBCLoginModule to group all roles possessed by a
user under a single Principal called "roles".
org.mortbay.jaas.spi.JDBCLoginModule
An example implementation of a LoginModule that uses a database to
store user names, passwords and roles. All database-related
information is configurable, including:
the names and columns of the user table and role table
the database connection driver, URL, username and password.

Using JAAS
Step 1: Configure the realm for your webapp context in the Jetty xml
configuration file:
<Call name="addWebApplication">
<Arg>/jaas/*</Arg>
<Arg><SystemProperty name="jetty.home"/>/extra/plus/demo/webapps/jaas</Arg>

<Set name="Realm">
<New class="org.mortbay.jaas.JAASUserRealm">
<Set name="Name">Test JAAS Realm</Set>
<Set name="LoginModuleName">jdbc</Set>
<Set name="RoleCheckPolicy">
<New class="org.mortbay.jaas.StrictRoleCheckPolicy"/>
</Set>
<Set name="CallbackHandlerClass">
org.mortbay.jaas.callback.DefaultCallbackHandler
</Set>
</New>
</Set>
</Call>

Note that it is only actually necessary to specify the RoleCheckPolicy
or CallbackHandlerClass if you have provided custom implementations of
them.

Step 2: Configure some security constraints and a login method in your
web.xml file, eg:

<security-constraint>
<web-resource-collection>
<web-resource-name>JAAS Role</web-resource-name>
<url-pattern>/doit/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>roleA</role-name>
</auth-constraint>
</security-constraint>

<login-config>
<auth-method>FORM</auth-method>
<realm-name>Test JAAS Realm</realm-name>
<form-login-config>
<form-login-page>/login.html </form-login-page>
<form-error-page>/error401.html </form-error-page>
</form-login-config>
</login-config>

Step 3: Create a login module configuration file. This one is from the
Jetty JAAS demo (in extra/etc/login.conf):
// sample login config file for the Jetty JDBCLoginModule
// if you change the database and need to specify a password,
set the property dbPassword
jdbc {
org.mortbay.jaas.spi.JDBCLoginModule required
debug="true"
dbUrl="jdbc:hsqldb:."
dbUserName="sa"
dbDriver="org.hsqldb.jdbcDriver"
userTable="myusers"
userField="myuser"
credentialField="mypassword"
userRoleTable="myuserroles"
userRoleUserField="myuser"
userRoleRoleField="myrole";
};

Note that the name of the module ("jdbc") must be the same as that
specified as the LoginModuleName in the Jetty xml config file in Step
1.
There is no particular schema required for the database tables storing
the authentication and role information. The properties userTable,
userField, credentialField, userRoleTable, userRoleUserField,
userRoleRoleField configure the names of the tables and the columns
within them that are used to format the following queries:

select <credentialField> from <userTable> where <userField> =?
select <userRoleRoleField> from <userRoleTable> where <userRoleUserField> =?

Step 4: Specify the location of the login configuration file on the
Jetty run line by setting the java.security.auth.login.config
property:
-Djava.security.auth.login.config=mylogin.conf

The above describes how to use the Jetty JAAS integration to
authenticate web users and authorize them against webapp security
constraints. It can also be used for authorization with a Java
security manager and permission policy file. For information on how to
accomplish this, build and run the JAAS demo in extra/plus as
instructed in the extra/plus/README.TXT file in the source
distribution.

Extension for extra fields with FORM login
As all servlet containers intercept and process a form submission with
action j_security_check, it is usually not possible to insert any
extra input fields onto a login form with which to perform
authentication: you may only pass j_username and j_password. For those
rare occasions when this is not good enough, and you require more
information from the user in order to authenticate them, you can use
the (new) JAAS callback handler
org.mortbay.jaas.callback.RequestParameterCallback. This callback
handler gives you access to all parameters that were passed in the
form submission. To use it:
Create a custom JAAS login module. Use the
org.mortbay.jaas.spi.JDBCLoginModule as an example.
In the login() method of your custom login module, add the
RequestParameterCallback to the list of callback handlers the login
module uses, tell it which params you are interested in, and then get
the value of the parameter back:
public boolean login()
throws LoginException
{
.
.
.
Callback[] callbacks = new Callback[3];
callbacks[0] = new NameCallback();
callbacks[1] = new ObjectCallback();

//as an example, look for a param named "extrainfo" in the request
//use one RequestParameterCallback() instance for each param
you want to access
callbacks[2] = new RequestParameterCallback ();
((RequestParameterCallback)callbacks[2]).setParameterName ("extrainfo");
.
.
.
callbackHandler.handle(callbacks);
String userName = ((NameCallback)callbacks[0]).getName();
Object pwd = ((ObjectCallback)callbacks[1]).getObject();
List paramValues =
((RequestParameterCallback)callbacks[2]).getParameterValues();

//use the userName, pwd and the value(s) of the parameter
named "extrainfo" to
//authenticate the user
.
.
.
}

Saludos,

José Luis Mayorga A.

--
"Hace tiempo estaba indeciso, pero ahora ya no estoy tan seguro"

Alejandro Narancio

unread,
Feb 18, 2006, 10:56:30 AM2/18/06
to jav...@googlegroups.com
Aquí les mando un ejemplo bien sencillo de como verificar que un usuario este logueado para acceder a ciertas páginas.
Obviamente el ejemplo es meramente academico y por eso carece de utilidad real (por ejemplo no pido password en la página de loguin ni verifico que el usuario exista, etc...) pero creo que puede aclararle un poquito este tema a aquellos que tienen dudas.


Saludos y espero que les sirva,

Alejandro
FilterExample.zip
Reply all
Reply to author
Forward
0 new messages