Tomcat Security

5 respostas
T

Galera, estou tendo problemas com o meu security do tomcat.
Quando eu coloco ele pra ler ditreto do arquivo tomcat users, ele funciona numa boa… mas quando eu tento fazer ele se conectar pelo banco, ele simplesmente não autentica… parecendo que ainda está tentando puxar algo do tomcat users…

O meu tomcat é o ultimo que tem, o 6. alguma coisa, baixei do site deles… e eu não tenho a pasta common dentro do catalina_home… eu tenho já direto na raiz a pasta lib, que contem os jars da aplicação tomcat, fui lá e adicionei o jar do mysql no qual estou mexendo… configurei também o server.xml pra receber dados do banco, porém ainda não se conecta pegando os usuários… fica aparecendo usuário e senhas inválidos…

Deem uma olhada…

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
        http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
    version="2.4">

    <description>
      Exemplo de autenticação e controle de acesso padrão J2EE
    </description>

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <jsp-config>
        <jsp-property-group>
           <url-pattern>/*</url-pattern>
           <page-encoding>UTF-8</page-encoding>
        </jsp-property-group>
    </jsp-config>

    <security-constraint>
        <web-resource-collection>
            <web-resource-name>Paginas do Usuario</web-resource-name>
            <url-pattern>/usuarios/*</url-pattern>
        </web-resource-collection>
        <auth-constraint>
            <role-name>usuario</role-name>
        </auth-constraint>
    </security-constraint>

    <security-constraint>
        <web-resource-collection>
            <web-resource-name>Paginas do Administrador</web-resource-name>
            <url-pattern>/admin/*</url-pattern>
        </web-resource-collection>
        <auth-constraint>
            <role-name>admin</role-name>
        </auth-constraint>
    </security-constraint>

    <security-role>
        <role-name>usuario</role-name>
    </security-role>
    <security-role>
        <role-name>admin</role-name>
    </security-role>

    <login-config>
        <auth-method>FORM</auth-method>
        <form-login-config>
            <form-login-page>/login.jsp</form-login-page>
            <form-error-page>/loginInvalido.jsp</form-error-page>
        </form-login-config>
    </login-config>

    <error-page>
        <error-code>403</error-code>
        <location>/erro403.jsp</location>
    </error-page>
        
</web-app>

index.jsp

<html>
<body>
<h1>Segurança J2EE (Form)<hr></h1>
<p>
<a href="usuarios/">Páginas dos usuários</a>
<p>
<a href="admin/">Páginas dos administradores</a>
<p>
<a href="logoff.jsp">Logoff</a>
</body>
</html>

login.jsp

<html>
<body>
<%
    request.getSession().setAttribute("pagina", request.getRequestURL());
%>
<h1>Demo de Segurança J2EE (Form)<hr></h1>
<p>
Esta página só pode ser acessada por usuários autenticados
<form method="post" action="j_security_check">
<table>
<tr><td>Login:</td>
<td><input size="15" name="j_username">
</tr>
<tr><td>Senha:</td>
<td><input type="password" size="15" name="j_password">
</tr>
<tr><td colpsan="2"><input type="submit" value=" Ok ">
</tr>
</table>
</form>
</body>
</html>

server.xml

<Engine name="Catalina" defaultHost="localhost">

    <Realm  className="org.apache.catalina.realm.JDBCRealm" debug="99"
               driverName="com.mysql.jdbc.Driver"
               connectionURL="jdbc:mysql://localhost/thiago"
               connectionName="root" connectionPassword="root"
               userTable="users" userNameCol="user_name" userCredCol="user_pass"
               userRoleTable="user_roles" roleNameCol="role_name" />

mysql

mysql> select * from user_roles;
+-----------+-----------+
| user_name | role_name |
+-----------+-----------+
| admin     | admin     |
| eperthi   | usuario   |
+-----------+-----------+
2 rows in set (0.00 sec)

mysql> select * from users;
+-----------+-----------+
| user_name | user_pass |
+-----------+-----------+
| admin     | admin     |
| eperthi   | 250586    |
+-----------+-----------+
2 rows in set (0.00 sec)

mysql> select * from role;
+---------+
| role    |
+---------+
| admin   |
| usuario |
+---------+
2 rows in set (0.00 sec)

5 Respostas

T

Talvez seja aqui meu problema… porque do jeito que está configurado, ele vai acessar o tomcat-users… como posso fazer para que isso seja alterado e busque em minha base de dados os usuários???

<GlobalNamingResources>

    <!-- Editable user database that can also be used by
         UserDatabaseRealm to authenticate users
    -->
    <Resource name="UserDatabase" auth="Container"
              type="org.apache.catalina.UserDatabase"
              description="User database that can be updated and saved"
              factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
              pathname="conf/tomcat-users.xml" />
  </GlobalNamingResources>
Rubem_Azenha

Estranho, posta o teu server.xml completo.

T
<?xml version='1.0' encoding='utf-8'?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<!-- Note:  A "Server" is not itself a "Container", so you may not
     define subcomponents such as "Valves" at this level.
     Documentation at /docs/config/server.html
 -->
<Server port="8005" shutdown="SHUTDOWN">

  <!--APR library loader. Documentation at /docs/apr.html -->
  <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
  <!--Initialize Jasper prior to webapps are loaded. Documentation at /docs/jasper-howto.html -->
  <Listener className="org.apache.catalina.core.JasperListener" />
  <!-- JMX Support for the Tomcat server. Documentation at /docs/non-existent.html -->
  <Listener className="org.apache.catalina.mbeans.ServerLifecycleListener" />
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />

  <!-- Global JNDI resources
       Documentation at /docs/jndi-resources-howto.html
  -->
  <GlobalNamingResources>

    <!-- Editable user database that can also be used by
         UserDatabaseRealm to authenticate users
    -->
    <Resource name="UserDatabase" auth="Container"
              type="org.apache.catalina.UserDatabase"
              description="User database that can be updated and saved"
              factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
              pathname="conf/tomcat-users.xml" />
  </GlobalNamingResources>

  <!-- A "Service" is a collection of one or more "Connectors" that share
       a single "Container" Note:  A "Service" is not itself a "Container",
       so you may not define subcomponents such as "Valves" at this level.
       Documentation at /docs/config/service.html
   -->
  <Service name="Catalina">

    <!--The connectors can use a shared executor, you can define one or more named thread pools-->
    <!--
    <Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
        maxThreads="150" minSpareThreads="4"/>
    -->


    <!-- A "Connector" represents an endpoint by which requests are received
         and responses are returned. Documentation at :
         Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)
         Java AJP  Connector: /docs/config/ajp.html
         APR (HTTP/AJP) Connector: /docs/apr.html
         Define a non-SSL HTTP/1.1 Connector on port 8080
    -->
    <Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
    <!-- A "Connector" using the shared thread pool-->
    <!--
    <Connector executor="tomcatThreadPool"
               port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
    -->
    <!-- Define a SSL HTTP/1.1 Connector on port 8443
         This connector uses the JSSE configuration, when using APR, the
         connector should be using the OpenSSL style configuration
         described in the APR documentation -->
    <!--
    <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
               maxThreads="150" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS" />
    -->

    <!-- Define an AJP 1.3 Connector on port 8009 -->
    <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />


    <!-- An Engine represents the entry point (within Catalina) that processes
         every request.  The Engine implementation for Tomcat stand alone
         analyzes the HTTP headers included with the request, and passes them
         on to the appropriate Host (virtual host).
         Documentation at /docs/config/engine.html -->

    <!-- You should set jvmRoute to support load-balancing via AJP ie :
    <Engine name="Standalone" defaultHost="localhost" jvmRoute="jvm1">
    -->
    <Engine name="Catalina" defaultHost="localhost">

    <Realm  className="org.apache.catalina.realm.JDBCRealm" debug="99"
               driverName="com.mysql.jdbc.Driver"
               connectionURL="jdbc:mysql://localhost/thiago"
               connectionName="root" connectionPassword="root"
               userTable="users" userNameCol="user_name" userCredCol="user_pass"
               userRoleTable="user_roles" roleNameCol="user_name" />

      <!--For clustering, please take a look at documentation at:
          /docs/cluster-howto.html  (simple how to)
          /docs/config/cluster.html (reference documentation) -->
      <!--
      <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
      -->

      <!-- The request dumper valve dumps useful debugging information about
           the request and response data received and sent by Tomcat.
           Documentation at: /docs/config/valve.html -->
      <!--
      <Valve className="org.apache.catalina.valves.RequestDumperValve"/>
      -->

      <!-- This Realm uses the UserDatabase configured in the global JNDI
           resources under the key "UserDatabase".  Any edits
           that are performed against this UserDatabase are immediately
           available for use by the Realm.  -->
      <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
             resourceName="UserDatabase"/>

      <!-- Define the default virtual host
           Note: XML Schema validation will not work with Xerces 2.2.
       -->
      <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true"
            xmlValidation="false" xmlNamespaceAware="false">

        <!-- SingleSignOn valve, share authentication between web applications
             Documentation at: /docs/config/valve.html -->
        <!--
        <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
        -->

        <!-- Access log processes all example.
             Documentation at: /docs/config/valve.html -->
        <!--
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log." suffix=".txt" pattern="common" resolveHosts="false"/>
        -->
<Context path="\projeto" reloadable="true" docBase="C:\Users\eperthi\workspace\projeto\web" workDir="C:\Users\eperthi\workspace\projeto\work" />


<Context path="/j2ee" reloadable="true" docBase="C:\Users\eperthi\workspace\seguranca-j2ee\seguranca" workDir="C:\Users\eperthi\workspace\seguranca-j2ee\work" />

      </Host>
    </Engine>
  </Service>
</Server>
Rubem_Azenha

tenta apagar ou comentar:

Linha 40:

<Resource name="UserDatabase" auth="Container"  
               type="org.apache.catalina.UserDatabase"  
               description="User database that can be updated and saved"  
               factory="org.apache.catalina.users.MemoryUserDatabaseFactory"                 pathname="conf/tomcat-users.xml" />

Linha 128 e 129

<Realm className="org.apache.catalina.realm.UserDatabaseRealm"  
            resourceName="UserDatabase"/>
T

Agora sim em Rubem…
Funcionou mano… mudei até a senha no banco para ver se realmente estaria logando…

Vou fazer alguns testes aqui e ver o que vai acontecer… dando tudo certo, vou aplicar em outras aplicações minhas…

Muito obrigado cara, vlw…

Criado 25 de julho de 2008
Ultima resposta 25 de jul. de 2008
Respostas 5
Participantes 2