Problema com atutenticação utilizando JAAS

0 respostas
S

Bom dia Galera,

Estou com problema de exibição de pagina após a autenticação utilizando o JAAS. Debuguei todo o codigo e esta tudo correto, faz a chamada ao WSLoginModule e ao final seta os valores para a role.

Ele esta dando o seguinte erro quando tenta acessar a pagina após a autenticação.

Estou utilizando o servidor JBOSS.

Erro de acesso a pagina:

HTTP Status 403 - Access to the requested resource has been denied

type Status report

message Access to the requested resource has been denied

description Access to the specified resource (Access to the requested resource has been denied) has been forbidden.

Segue a configuração que realizei para o JAAS:

1º Passo: Configurei o arquivo dentro do JBOSS: login-config.xml

<application-policy name="WSLoginModule">
      <authentication>
        <login-module code="br.com.guj.security.principals.GujLoginModule" flag="required">
           <module-option name="sqlUser">select senha from tb_usuario where login=?</module-option>
          <module-option name="sqlRoles">select id_role from tb_usuario_roles where login=?</module-option>
          <module-option name="unauthenticatedIdentity">anonymous</module-option>
        </login-module>
      </authentication>
    </application-policy>

2º Passo:

O Código abaixo foi retirado do seguinte tutorial: http://www.guj.com.br/article.show.logic?id=184

package br.com.guj.security.principals;  
import java.security.Principal;  
 import java.util.Set;  
   
/** 
 * @author fabio.viana 
 */  
public class User implements Principal{  
   private String name;  
   private Set roles;  
      
    public User(String name){  
         this.name = name;  
     }  
      
     public String getName() {  
         return name;  
   }  
       
     public Set getRoles() {  
         return roles;  
    }  
  
     public void setRoles(Set roles) {  
         if (this.roles == null)  
              this.roles = roles;  
     }  
 }


 package br.com.guj.security.principals;  
  import java.security.Principal;  
    
  /** 
   * @author fabio.viana 
   */  
  public class Role implements Principal{  
     private String name;  
       
     public Role(String name){  
         this.name = name;  
     }  
       
     public String getName() {  
         return name;  
     }  
  }    


package br.com.guj.security.principals;

import java.sql.*;
 import java.util.*;
 import javax.naming.*;
 import javax.security.auth.*;
 import javax.security.auth.callback.*;
 import javax.security.auth.login.LoginException;
 import javax.security.auth.spi.LoginModule;
import javax.sql.DataSource;

 /**
  * @author fabio.viana   */

 public class GujLoginModule implements LoginModule {
    private boolean commitSucceeded = false;
    private boolean succeeded = false;

    private User user;
    private Set roles = new HashSet();

    protected Subject subject;
    protected CallbackHandler callbackHandler;
    protected Map sharedState;
    private String dataSourceName;
    private String sqlUser;
    private String sqlRoles;

    public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options) {
        this.subject = subject;
        this.callbackHandler = callbackHandler;
        this.sharedState = sharedState;
        dataSourceName = (String) options.get("dataSourceName");
        sqlUser = (String) options.get("sqlUser");
        sqlRoles = (String) options.get("sqlRoles");
    }

    public boolean login() throws LoginException {

        

        // recupera o login e senha informados no form
        getUsernamePassword();

        Connection conn = null;
        try {
            // obtem a conexão
            try {
                Context initContext = new InitialContext();
                DataSource ds = (DataSource)initContext.lookup("java:jdbc/JNDISecurity");
                conn = ds.getConnection();
            } catch (NamingException e) {
                succeeded = false;
                throw new LoginException("Erro ao recuperar DataSource: " + e.getClass().getName() + ": " + e.getMessage());
            } catch (SQLException e) {
                succeeded = false;
                throw new LoginException("Erro ao obter conexão: " + e.getClass().getName() + ": " + e.getMessage());
            }
            // valida o usuario
            validaUsuario(conn);
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                }
            }
        }
        // acidiona o usuario e roles no mapa de compartilhamento
        sharedState.put("javax.security.auth.principal", user);
        sharedState.put("javax.security.auth.roles", roles);

        return true;
    }

    public boolean commit() throws LoginException {
        // adiciona o usuario no principals
        if (user != null && !subject.getPrincipals().contains(user)) {
            subject.getPrincipals().add(user);
        }
        // adiciona as roles no principals
        if (roles != null) {
            Iterator it = roles.iterator();
            while (it.hasNext()) {
                Role role = (Role) it.next();
                if (!subject.getPrincipals().contains(role)) {
                    subject.getPrincipals().add(role);
                }
            }
        }

        commitSucceeded = true;
        return true;
    }

    public boolean abort() throws LoginException {
        if (!succeeded) {
            return false;
        } else if (succeeded && !commitSucceeded) {
            succeeded = false;
        } else {
            succeeded = false;
            logout();
        }

        this.subject = null;
        this.callbackHandler = null;
        this.sharedState = null;
        this.roles = new HashSet();

        return succeeded;
    }

    public boolean logout() throws LoginException {
        // remove o usuario e as roles do principals
        subject.getPrincipals().removeAll(roles);
        subject.getPrincipals().remove(user);
        return true;
    }

    /**
     * Valida login e senha no banco
     */
    private void validaUsuario(Connection conn) throws LoginException {
        String senhaBanco = null;
        PreparedStatement statement = null;
        ResultSet rs = null;
        try {
            statement = conn.prepareStatement(sqlUser);
            statement.setString(1, loginInformado);
            rs = statement.executeQuery();
            if (rs.next()) {
                senhaBanco = rs.getString(1);
            } else {
                succeeded = false;
                throw new LoginException("Usuário não localizado.");
            }
        } catch (SQLException e) {
            succeeded = false;
            throw new LoginException("Erro ao abrir sessão: "
                    + e.getClass().getName() + ": " + e.getMessage());
        } finally {
            try {
                if (rs != null)
                    rs.close();
                if (statement != null)
                    statement.close();
            } catch (Exception e) {

            }
        }

        if (senhaInformado.equals(senhaBanco)) {
            //user = new User(login);
            user = new User(loginInformado);
            recuperaRoles(conn);
            user.setRoles(roles);
            return;
        } else {
            throw new LoginException("Senha Inválida.");
        }
    }

    /**
     * Recupera as roles no banco
     */
    public void recuperaRoles(Connection conn) throws LoginException {
        PreparedStatement statement = null;
        ResultSet rs = null;
        try {
            statement = conn.prepareStatement(sqlRoles);
            statement.setString(1, loginInformado);
            rs = statement.executeQuery();
            while (rs.next()) {
                roles.add(new Role(rs.getString(1)));
            }
            roles.add(new Role("LOGADO"));
        } catch (SQLException e) {
            succeeded = false;
            throw new LoginException("Erro ao recuperar roles: " + e.getClass().getName() + ": " + e.getMessage());
        } finally {
            try {
                if (rs != null)
                    rs.close();
                if (statement != null)
                    statement.close();
            } catch (Exception e) {

            }
        }
    }

    /**
     * Login do usuário.
     */
    protected String loginInformado;

    /**
     * Senha do usuário.
     */
    protected String senhaInformado;

    /**
     * Obtem o login e senha digitados
     */
    protected void getUsernamePassword() throws LoginException {
        if (callbackHandler == null)
            throw new LoginException("Error: no CallbackHandler available to garner authentication information from the user");

        Callback[] callbacks = new Callback[2];
        callbacks[0] = new NameCallback("Login");
        callbacks[1] = new PasswordCallback("Senha", false);
        try {
            callbackHandler.handle(callbacks);
            loginInformado = ((NameCallback) callbacks[0]).getName();
            char[] tmpPassword = ((PasswordCallback) callbacks[1]).getPassword();
            senhaInformado = new String(tmpPassword);
            ((PasswordCallback) callbacks[1]).clearPassword();
        } catch (java.io.IOException ioe) {
            throw new LoginException(ioe.toString());
        } catch (UnsupportedCallbackException uce) {
            throw new LoginException("Error: " + uce.getCallback().toString() + " not available to garner authentication information from the user");
        }
    }
 }

3º Configuerei o Web.xml

<!-- Lista de Roles -->   
    <security-role>   
        <description>Quando usuario estiver logado</description>   
        <role-name>LOGADO</role-name>   
    </security-role>   
       
    <security-role>   
        <description>Administrador, pode fazer tudo</description>   
        <role-name>ADM</role-name>
    </security-role>   
       
    <security-role>   
        <description>Para cadastrar cliente, deve se ter esta role</description>   
        <role-name>CAD_CLIENTE</role-name>   
    </security-role>  

    <!-- Restrições -->
    <security-constraint>   
        <display-name>Cadastro de Clientes</display-name>
        <web-resource-collection>   
            <web-resource-name>Cadastro de Clientes</web-resource-name>
            <url-pattern>/Teste.jsp</url-pattern>
        </web-resource-collection>
        <auth-constraint>
            <role-name>ADM</role-name>
            <role-name>LOGADO</role-name>
        </auth-constraint>   
    </security-constraint>   

    <login-config>
        <auth-method>FORM</auth-method>
        <realm-name>default</realm-name>
        <form-login-config>
            <form-login-page>/login.jsp</form-login-page>
            <form-error-page>/erro.jsp</form-error-page>
        </form-login-config>
    </login-config>

4º Criei a pagina de login:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        
        <form method="POST" action="j_security_check">
                Usuário: <input type="text" name="j_username" size="15"><br>
                Senha: <input type="password" name="j_password" maxlength="20" size="15">
                <input type=submit value="OK">

    </form>  
    </body>
</html>

5º Criei a pagina Teste.jsp

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        Hello World!
    </body>
</html>

Agradeço galera se alguem puder me ajudar…

Pelo que eu estou vendo deve ser algum erro de configuração, mais não estou conseguindo ver este problema.

Abcss

Criado 12 de maio de 2009
Respostas 0
Participantes 1