JAAS + JBoss + LoginModule não Autoriza! [RESOLVIDO]

Boa tarde pessoas!

Estou tentando implementar jaas no Jboss.

Já configurei os xml’s tanto da aplicação web quanto do servidor para encontrar meu .jar em que implementa o LoginModule.

Consegui debugar todo o código e vi que chega até o fim sem dar erro, ou seja, ele executa o método ‘commit’ e retorna true!!!

Mas quando a página termina de carregar, ao invés de entrar na minha aplicação aparece o seguinte:
HTTP Status 403 - Access to the requested resource has been denied

Já verifiquei o web.xml, tenho dentro da pasta conf do jboss os aquivos de usuario e role, e setei hardcode o meu usuário e role, só pra ter certeza que estava passando o parametro certo. Mas apesar de tudo aparentar estar indo bem, ele não deixa entrar na aplicação!!!

Alguem pode me dar uma luz???

Obrigada! :slight_smile:

Gente, eu só precisava ao menos de uma luz sobre o que pode estar dando errado…

Minha classe LoginModule está assim:

package br.com.seguranca;

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 br.com.guj.security.principals.
;
import javax.sql.DataSource;

import br.com.seguranca.principals.Role;
import br.com.seguranca.principals.User;

/**

  • @author Paula Covo.
    */
    public class LoginModuleVida 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(“dsJndiName”);
    sqlUser = “select SENHA from USUARIO where LOGIN = ?”;//(String) options.get(“sqlUser”);
    sqlRoles = “select ID_ROLE from USUARIO_ROLES where LOGIN = ?”;//(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();
    

// Context envContext = (Context) initContext.lookup(“java:/comp/env”);
// DataSource ds = (DataSource) envContext.lookup(dataSourceName);
// DataSource ds = (DataSource) initContext.lookup(dataSourceName);

               /***/ //TODO
               
               try {
   				Class.forName("oracle.jdbc.driver.OracleDriver");
       			} catch (ClassNotFoundException e) {
       				throw new SQLException("Não foi possivel obter instância do OracleDriver: "+e.getMessage(),e);
       			}
       			try {
       				conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system", "adminadmin");
       			} catch (SQLException e) {
       				throw new SQLException("Não foi possivel obter instância de" +
       					  " Connection atravé do DriverManager: "+e.getMessage());
       			}
               
               /***/

// 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 = "paula";//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(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 {
	  System.out.println(" PAULA 01 - getUsernamePassword ");
      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");
     }
}

}

Tem algo que está faltando? Sobrando???
Please!!! :slight_smile:

No meu login-config.xml eu coloquei isso:

<application-policy name="myjaas"> 
	<authentication> 
		<login-module code="br.com.seguranca.LoginModuleVida" flag="required">
		</login-module> 
	</authentication> 
</application-policy>

Pois tanto usuário quanto role estão hardcode.

Alguém??? :lol:

Ainda não encontrei solução para o meu problema…

Mas vi que talvez esteja faltando o jboss.xml com a tag <security-domain> e as minhas roles…

Só que eu não sei como construir esse xml e nem o diretório correto onde ele deveria ficar.

Alguém sabe me orientar quanto a isto?

Obrigada novamente! :slight_smile:

Olá novamente pessoas! :slight_smile:

Consegui resolver parte do meu problema (ao menos autoriza agora!).

O que eu fiz:

1- Criei uma página login.jsp com o seguinte form:
<form method=“POST” action=“j_security_check”>

Usuário: <input type=“text” name=“j_username” size=“15”>

Senha: <input type=“password” name=“j_password” maxlength=“20” size=“15”>

<input type=“submit” value=“Enviar”/>

</form>

2- Criei uma página error_login.jsp com o seguinte form:
<form method=“POST” action=“j_security_check”>

Usuário ou senha incorretos.

Usuário: <input type=“text” name=“j_username” size=“15”>

Senha: <input type=“password” name=“j_password” maxlength=“20” size=“15”>

<input type=“submit” value=“Enviar”/>

</form>

3- Configurei no WEB.XML da minha aplicação web:
<login-config>
<auth-method>FORM</auth-method>
<realm-name>myjaas</realm-name>
<form-login-config>
<form-login-page>/jsp/security/login.jsp</form-login-page>
<form-error-page>/jsp/security/error_login.jsp</form-error-page>
</form-login-config>
</login-config>

<security-constraint>
<web-resource-collection>
<web-resource-name>home</web-resource-name>
<url-pattern>*</url-pattern>
<http-method>GET</http-method>
<http-method>POST</http-method>
</web-resource-collection>
<auth-constraint>
<role-name>LOGADO</role-name>
</auth-constraint>
</security-constraint>

<security-role>
<role-name>LOGADO</role-name>
</security-role>

4 - Dentro de sua aplicação web, dentro da pasta WEB-INF, crie um xml com o nome de jboss-web.xml com o seguinte conteúdo:

<?xml version="1.0" encoding="UTF-8"?>

<jboss-web>
<security-domain>java:/jaas/myjaas</security-domain>
</jboss-web>

5 - Dentro do diretório home do jboss, na pasta ‘jboss-4.2.3.GA\server\default\conf’ coloque dentro do arquivo login-config.xml, dentro da tag policy:

&lt;application-policy name = "myjaas"&gt;
   &lt;authentication&gt;
      &lt;login-module code="br.com.seguranca.MeuLoginModule" flag = "required"&gt;
      &lt;/login-module&gt;
   &lt;/authentication&gt;
&lt;/application-policy&gt;

6 - Crie um .jar com uma classe que estenda a classe UsernamePasswordLoginModule (classe de uma biblioteca do jboss). Não sei se é necessário, mas na dúvida eu dei o nome do meu jar com o mesmo nome da application-policy name (mas acho que isso não é necessário não: myjaas.jar):

package br.com.seguranca;

import java.security.acl.Group;
import java.util.Map;

import javax.security.auth.Subject;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.login.LoginException;

import org.jboss.security.SimpleGroup;
import org.jboss.security.SimplePrincipal;
import org.jboss.security.auth.spi.UsernamePasswordLoginModule;

public class MeuModuleVida extends UsernamePasswordLoginModule {

// protected SimplePrincipal p;

public LoginModuleVida() {
	super();
}

@Override
public void initialize(Subject subject, CallbackHandler callbackHandler,
		Map sharedState, Map options) {
	super.initialize(subject, callbackHandler, sharedState, options);
}

@Override
protected String getUsersPassword() throws LoginException {
	return "paula";
}

@Override
protected boolean validatePassword(String inputPassword,
		String expectedPassword) {
	boolean isValid = false;
	if (inputPassword != null) {
		try {
			String username = getUsername();
			isValid = true;
		} catch (Throwable e) {
			e.printStackTrace();
			super.setValidateError(e);
		}
	}
	return isValid;
}

@Override
protected Group[] getRoleSets() throws LoginException {
	SimpleGroup userRoles = new SimpleGroup("Roles");
	userRoles.addMember(new SimplePrincipal("LOGADO"));
	Group[] roleSets = { userRoles };
	return roleSets;
}

}

7 - coloque este jar dentro do diretório lib ‘jboss-4.2.3.GA\server\default\lib’.

PRONTO.

Desta forma consegui que o jaas fizesse a autenticação e autorização a partir do meu código.

Lá está hardcode a senha e as roles. Mas desta forma posso substituir o hardcode por uma pesquisa no banco de dados.

MAS AINDA FICA UMA DÚVIDA:
Como implemento isto sem necessariamente ter que usar a biblioteca do jboss, ou seja, usando só bibliotecas do java?
Pois implementando só com bibliotecas do java, o jboss só autentica, mas não autoriza.
ALGUÉM SABE ME DIZER O PORQUE???

Valew!!! :slight_smile:

Para implementar o LoginModule para o JBoss sem precisar usar as bibliotecas do jboss:

Ao invés de adicionar a role direto ao Principal de Subject (subject.getPrincipals().add(role)), crio um Group que irá conter minhas roles e aí sim adiciono meu Group:

Group group = new MyGroup(“Roles”);
for (MyPrincipal role : roles) {
group.addMember(role);
}
subject.getPrincipals().add(group);

Desta forma, além do jboss autenticar, ele consegue autorizar. Pois depende deste objeto Group para visualizar as roles.

Caso tenha mais de um grupo de roles (uma coleção Group[]), basta itera-la e para cada objeto do tipo Group fazer subject.getPrincipals().add(group);

:lol:

Valeu Paula!

Estava exatamento com o mesmo problema, ele autenticava o user mas não autorizava conforme a role.

Seguindo este seu raciocínio de adicionar as roles em um grupo antes de adicionar ao Subject funcionou!

Utilizei esta implementação para o Group:

/*
 * Copyright 1996-2006 Sun Microsystems, Inc.  All Rights Reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Sun designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Sun in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
 * CA 95054 USA or visit www.sun.com if you need additional information or
 * have any questions.
 */

package sun.security.acl;

import java.util.*;
import java.security.*;
import java.security.acl.*;

/**
 * This class implements a group of principals.
 * @author      Satish Dharmaraj
 */
public class GroupImpl implements Group {
    private Vector<Principal> groupMembers = new Vector<Principal>(50, 100);
    private String group;

    /**
     * Constructs a Group object with no members.
     * @param groupName the name of the group
     */
    public GroupImpl(String groupName) {
        this.group = groupName;
    }

    /**
     * adds the specified member to the group.
     * @param user The principal to add to the group.
     * @return true if the member was added - false if the
     * member could not be added.
     */
    public boolean addMember(Principal user) {
        if (groupMembers.contains(user))
          return false;

        // do not allow groups to be added to itself.
        if (group.equals(user.toString()))
            throw new IllegalArgumentException();

        groupMembers.addElement(user);
        return true;
    }

    /**
     * removes the specified member from the group.
     * @param user The principal to remove from the group.
     * @param true if the principal was removed false if
     * the principal was not a member
     */
    public boolean removeMember(Principal user) {
        return groupMembers.removeElement(user);
    }

    /**
     * returns the enumeration of the members in the group.
     */
    public Enumeration<? extends Principal> members() {
        return groupMembers.elements();
    }

    /**
     * This function returns true if the group passed matches
     * the group represented in this interface.
     * @param another The group to compare this group to.
     */
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (obj instanceof Group == false) {
            return false;
        }
        Group another = (Group)obj;
        return group.equals(another.toString());
    }

    // equals(Group) for compatibility
    public boolean equals(Group another) {
        return equals((Object)another);
    }

    /**
     * Prints a stringified version of the group.
     */
    public String toString() {
        return group;
    }

    /**
     * return a hashcode for the principal.
     */
    public int hashCode() {
        return group.hashCode();
    }

    /**
     * returns true if the passed principal is a member of the group.
     * @param member The principal whose membership must be checked for.
     * @return true if the principal is a member of this group,
     * false otherwise
     */
    public boolean isMember(Principal member) {

        //
        // if the member is part of the group (common case), return true.
        // if not, recursively search depth first in the group looking for the
        // principal.
        //
        if (groupMembers.contains(member)) {
            return true;
        } else {
            Vector<Group> alreadySeen = new Vector<Group>(10);
            return isMemberRecurse(member, alreadySeen);
        }
    }

    /**
     * return the name of the principal.
     */
    public String getName() {
        return group;
    }

    //
    // This function is the recursive search of groups for this
    // implementation of the Group. The search proceeds building up
    // a vector of already seen groups. Only new groups are considered,
    // thereby avoiding loops.
    //
    boolean isMemberRecurse(Principal member, Vector<Group> alreadySeen) {
        Enumeration<? extends Principal> e = members();
        while (e.hasMoreElements()) {
            boolean mem = false;
            Principal p = (Principal) e.nextElement();

            // if the member is in this collection, return true
            if (p.equals(member)) {
                return true;
            } else if (p instanceof GroupImpl) {
                //
                // if not recurse if the group has not been checked already.
                // Can call method in this package only if the object is an
                // instance of this class. Otherwise call the method defined
                // in the interface. (This can lead to a loop if a mixture of
                // implementations form a loop, but we live with this improbable
                // case rather than clutter the interface by forcing the
                // implementation of this method.)
                //
                GroupImpl g = (GroupImpl) p;
                alreadySeen.addElement(this);
                if (!alreadySeen.contains(g))
                  mem =  g.isMemberRecurse(member, alreadySeen);
            } else if (p instanceof Group) {
                Group g = (Group) p;
                if (!alreadySeen.contains(g))
                  mem = g.isMember(member);
            }

            if (mem)
              return mem;
        }
        return false;
    }
}

(http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/sun/security/acl/GroupImpl.java#GroupImpl)

e no comit, onde itero as roles :

if (roles != null) {
			Iterator<Role> it = roles.iterator();
			
			Group group = new GroupImpl("Roles");
			
			while (it.hasNext()) {
				Role role = it.next();
					group.addMember(role);
				subject.getPrincipals().add(group); 
			}