[resolvido]JAAS + JSF + JBOSS

1 resposta
anagrrrl

Bom dia,

estou configurando o JAAS numa aplicação que usa JSF+JBOSS 4.2 e não estou conseguindo. Será que alguém pode me ajudar. Seguem os arquivos:

jboss-web.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE jboss-web PUBLIC "-//JBoss//DTD Web Application 2.4//EN" "http://www.jboss.org/j2ee/dtd/jboss-web_5_0.dtd">
<jboss-web>
      <security-domain>java:/jaas/apoioIQ</security-domain>     
      <context-root>/apoioIQ</context-root>
</jboss-web>
parte do web.xml
<security-constraint>
    <web-resource-collection>
      <web-resource-name>Restricted to Secure role</web-resource-name>
      <url-pattern>/menu.jsf</url-pattern>
      <http-method>GET</http-method>
      <http-method>POST</http-method>
    </web-resource-collection>
    <web-resource-collection>
      <web-resource-name>Restricted to Secure role</web-resource-name>
      <url-pattern>/index.jsf</url-pattern>
      <http-method>GET</http-method>
      <http-method>POST</http-method>
    </web-resource-collection>
    <auth-constraint>
      <role-name>financeiro</role-name>
    </auth-constraint>
    <user-data-constraint>
      <transport-guarantee>NONE</transport-guarantee>
    </user-data-constraint>
  </security-constraint>
  <login-config>
    <auth-method>FORM</auth-method>
    <realm-name>apoioIQ</realm-name>
    <form-login-config>
      <form-login-page>/login.jsf</form-login-page>
      <form-error-page>/errorPage.jsf?errorCode=1</form-error-page>
    </form-login-config>
  </login-config>
  <security-role>
    <role-name>financeiro</role-name>
  </security-role>
Classes login module
public class ApoioIQLoginModule extends AbstractLoginModule{
	

	/**
	 * Método que inicializa os valores padrão do LoginModule.
	 */
	@SuppressWarnings("unchecked")
	public void initialize(Subject subject, CallbackHandler callbackHandler, Map sharedState, Map options){
		super.initialize(subject, callbackHandler, sharedState, options);

	}

	@SuppressWarnings("unchecked")
	protected Group[] getRoleSets() throws LoginException{
		String username = getUsername();
		HashMap setsMap = new HashMap();
		String name = "financeiro";
		String groupName = "Roles";

		Group group = (Group) setsMap.get(groupName);
		if( group == null ){
			group = new SimpleGroup(groupName);
			setsMap.put(groupName, group);
		}
		
		try	{
			Principal p = super.createIdentity(name);
			group.addMember(p);
		
		}catch(Exception e){
			log.debug("Erro ao criar principal: "+name, e);
		}
			

		Group[] roleSets = new Group[setsMap.size()];
		setsMap.values().toArray(roleSets);
		
		
			
			
			return roleSets;
	}

	protected String convertRawPassword(String rawPassword){
		return rawPassword;
	}
}




public abstract class AbstractLoginModule extends AbstractServerLoginModule
{
	private Principal identity;
	private char[] credential;

	/** (non-Javadoc)
	 * @see org.jboss.security.auth.spi.AbstractServerLoginModule#initialize(javax.security.auth.Subject, javax.security.auth.callback.CallbackHandler, java.util.Map, java.util.Map)
	 */
	@SuppressWarnings("unchecked")
	public void initialize(Subject subject, CallbackHandler callbackHandler,
			Map sharedState, Map options){
		super.initialize(subject, callbackHandler, sharedState, options);
		
	}

	/**
	 *  Método chamado para autenticar o usuario
	 */
	@SuppressWarnings("unchecked")
	public boolean login() throws LoginException
	{
		// See if shared credentials exist
		if( super.login() == true ){
			// Setup our view of the user
			Object username = sharedState.get("javax.security.auth.login.name");
			if( username instanceof Principal ){
				identity = (Principal) username;
			}else{
				String name = username.toString();
				try{
					identity = createIdentity(name);
				}catch(Exception e){
					log.debug("Failed to create principal", e);
					throw new LoginException("Failed to create principal: "+ e.getMessage());
				}
			}
			Object password = sharedState.get("javax.security.auth.login.password");
			if( password instanceof char[] ){
				credential = (char[]) password;
			}else if( password != null ){
				String tmp = password.toString();
				credential = tmp.toCharArray();
			}
			return true;
		}

		super.loginOk = false;
		String[] info = getUsernameAndPassword();
		String username = info[0];
		String password = info[1];
		if( username == null && password == null )
		{
			identity = unauthenticatedIdentity;
			super.log.trace("Authenticating as unauthenticatedIdentity="+identity);
		}

		if( identity == null ){
			try{
				identity = createIdentity(username);
			}catch(Exception e){
				log.debug("Failed to create principal", e);
				throw new LoginException("Failed to create principal: "+ e.getMessage());
			}
			
			try {
				if( validatePassword() == false )
				{
					super.log.debug("Bad password for username="+username);
					throw new FailedLoginException("Password Incorrect/Password Required");
				}
			} catch (SQLException e) {
				e.printStackTrace();
				super.log.debug("Bad password for username="+username);
				throw new FailedLoginException("Password Incorrect/Password Required");
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
				super.log.debug("Falha no driver oracle");
				throw new FailedLoginException("Falha no driver oracle");
			}
		}

		if( getUseFirstPass() == true )
		{    // Add the username and password to the shared state map
			sharedState.put("javax.security.auth.login.name", username);
			sharedState.put("javax.security.auth.login.password", credential.toString());
		}
		super.loginOk = true;
		super.log.trace("User '" + identity + "' authenticated, loginOk="+loginOk);
		return true;
	}

	protected Principal getIdentity()
	{
		return identity;
	}
	protected Principal getUnauthenticatedIdentity()
	{
		return unauthenticatedIdentity;
	}

	protected Object getCredentials()
	{
		return credential;
	}
	/**
	 * 
	 * 
	 * @return usuario
	 */
	protected String getUsername()
	{
		String username = null;
		if( getIdentity() != null )
			username = getIdentity().getName().split(";")[0];
		return username;
	}
	/**
	 * 
	 * 
	 * @return password
	 */
	protected String getPassword()
	{
		Object password = sharedState.get("javax.security.auth.login.password");
		String tmp = "";
		if( password instanceof char[] ){
			tmp = ((char[]) password).toString();
		}else if( password != null ){
			tmp = password.toString();
		}
		
		return tmp;
	}
	/**
	 * 
	 * 
	 * @return usuario
	 */
	protected String getDatabase()
	{
		String database = null;
		if( getIdentity() != null && getIdentity().getName().split(";").length > 1)
			database = getIdentity().getName().split(";")[1];
		return database;
	}

	/**
	 * Seta o usuário e a senha, através do callback
	 *  
     * @return String[], [0] = username, [1] = password
     * @exception LoginException thrown if CallbackHandler is not set or fails.
	 */
	protected String[] getUsernameAndPassword() throws LoginException
	{
		String[] info = {null, null};
		// prompt for a username and password
		if( callbackHandler == null )
		{
			throw new LoginException("Error: no CallbackHandler available " +
			"to collect authentication information");
		}
		NameCallback nc = new NameCallback("User name: ", "guest");
		PasswordCallback pc = new PasswordCallback("Password: ", false);
		Callback[] callbacks = {nc, pc};
		String username = null;
		String password = null;
		try
		{
			callbackHandler.handle(callbacks);
			username = nc.getName();
			char[] tmpPassword = pc.getPassword();
			if( tmpPassword != null )
			{
				credential = new char[tmpPassword.length];
				System.arraycopy(tmpPassword, 0, credential, 0, tmpPassword.length);
				pc.clearPassword();
				password = new String(credential);
			}
		}
		catch(java.io.IOException ioe)
		{
			throw new LoginException(ioe.toString());
		}
		catch(UnsupportedCallbackException uce)
		{
			throw new LoginException("CallbackHandler does not support: " + uce.getCallback());
		}
		info[0] = username;
		info[1] = password;
		return info;
	}

	/** Valida se o password é válido
     * @return true if the inputPassword is valid, false otherwise.
	 * @throws LoginException 
	 * @throws ClassNotFoundException 
	 * @throws SQLException 
	 */
	protected boolean validatePassword() throws LoginException, SQLException, ClassNotFoundException 
	{
		boolean valid = false;
		if( getUsername() == null || getPassword() == null || getDatabase() == null)
			return false;
		
		
		String[] s = {"",""};
		s = getUsernameAndPassword();
		
		Connection con = Conexao.getConnection(getUsername(), s[1] , getDatabase());

		valid = true;
		
		return valid;
	}


}
login-config.xml (JBOSS)
<application-policy name="apoioIQ">
      <authentication>
        <login-module code="br.com.unimed.cn.loginmodule.ApoioIQLoginModule" flag="required">
        
        </login-module>
      </authentication>
  </application-policy>

alguém pode me ajudar?

1 Resposta

anagrrrl

encontrei o problema, era minha função javascript q estava submetendo o form errado.

Criado 1 de novembro de 2010
Ultima resposta 1 de nov. de 2010
Respostas 1
Participantes 1