2

I am quite new to Java EE and was starting out with tomcat. I am developing a small task application with PrimeFaces.

The application has a main page and admin area which is protected by the web.xml file. When i develop the login page according to guidelines posted here http://docs.oracle.com/cd/E19159-01/819-3669/bncby/index.html. I cannot login although I have configured the realm properly.

I read this post on JSP web application form based authentication in tomcat which is exactly the problem I have. But I am not using Eclipse.
These are my codings and XML configuration files.

The login.jsp page

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Log In</title>
</head>
<body>
    <form method="post" action="j_security_check">
        <p>Username</p>
        <input type="text" name="j_username" />
        <p>Password</p>
        <input type="password" name="j_password" />
        <p></p>
        <input type="submit" value="Submit" /> <input type="reset"
            value="reset" />
    </form>
</body>
</html>

The web.xml file

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>ToDoApplication</display-name>
  <welcome-file-list>
    <welcome-file>index.xhtml</welcome-file>
  </welcome-file-list>

  <!-- JSF Mapping -->
  <servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
  </servlet>

  <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>/faces/*</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.jsf</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.faces</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.xhtml</url-pattern>
    </servlet-mapping>

    <security-constraint>
        <display-name>Main Login Auth</display-name>
        <web-resource-collection>
            <web-resource-name>Restricted Access</web-resource-name>
            <url-pattern>/admin/*</url-pattern>     
        </web-resource-collection>
        <auth-constraint>
            <role-name>admin</role-name>        
        </auth-constraint>
        <user-data-constraint>
            <transport-guarantee>NONE</transport-guarantee>     
        </user-data-constraint>
    </security-constraint>

    <security-role>
        <role-name>management</role-name>
    </security-role>
    <security-role>
        <role-name>sales</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>/error.jsp</form-error-page>       
        </form-login-config>
    </login-config>

</web-app>

This is my server.xml in tomcat/conf folder.

    <!-- 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">
  <!-- Security listener. Documentation at /docs/config/listeners.html
  <Listener className="org.apache.catalina.security.SecurityListener" />
  -->
  <!--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" />
  <!-- Prevent memory leaks due to use of particular java/javax APIs-->
  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
  <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" />

  <!-- 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 8081
    -->
    <Connector port="8081" 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 BIO implementation that requires the JSSE
         style configuration. When using the APR/native implementation, the
         OpenSSL style configuration is required as described in the APR/native
         documentation -->
    <!--
    <Connector port="8443" protocol="org.apache.coyote.http11.Http11Protocol"
               maxThreads="150" SSLEnabled="true" 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="Catalina" defaultHost="localhost" jvmRoute="jvm1">
    -->
    <Engine name="Catalina" defaultHost="localhost">

      <!--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"/>
      -->

      <!-- Use the LockOutRealm to prevent attempts to guess user passwords
           via a brute-force attack -->
      <Realm className="org.apache.catalina.realm.LockOutRealm">
        <!-- 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"/>
      </Realm>

<!-- Edited by Me while adding support to JDBC database configuration -->
<context path="/ToDoApplication" privileged="true" reloadable="true" cookies="true" debug="true">
<Realm className="org.apache.catalina.realm.JDBCRealm"
            driverName="com.mysql.jdbc.Driver"
            connectionURL="jdbc:mysql://localhost/todo?user=tomcat&amp;password=tomcat"
            userTable="users" userNameCol="username" userCredCol="password"
         userRolesTable="user_roles" roleNameCol="rolename"/>
</context>

<!-- Editing finished -->




      <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">

        <!-- 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
             Note: The pattern used is equivalent to using pattern="common" -->
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log." suffix=".txt"
               pattern="%h %l %u %t &quot;%r&quot; %s %b" />

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

This is how I have prepared the database tables, database is called 'todo'.

mysql> SELECT * FROM users;
+----------+----------+
| username | password |
+----------+----------+
| lal      | lal      |
| lala     | lala     |
| mad      | mada     |
| nalaka   | nalaka   |
+----------+----------+
4 rows in set (0.00 sec)

mysql> SELECT * FROM user_roles;
+----------+------------+
| username | rolename   |
+----------+------------+
| lal      | sales      |
| lala     | management |
| lala     | sales      |
| mad      | admin      |
| nalaka   | sales      |
+----------+------------+
5 rows in set (0.00 sec)

I have to use user mad to login because in the web.xml file I have specified the role as admin to login to the admin area. When I use the username and password as mad and mada respectively, I get redirected to the error page. And the URL is appended with j_security_check like this.

http://localhost:8081/ToDoApplication/admin/j_security_check

The database user tomcat has SELECT privileges for the todo database. The tomcat guide mentioned that since the tomcat server wont be writing to the database, the user must at least have read privileges.

Community
  • 1
  • 1
LalakaJ
  • 531
  • 7
  • 16
  • there is no *.jsp in your Facesservlet configuration, but if u were to use the FacesServlet, it would need to be a h:form/h:body. Using JPA would be easier, but as you're using sql - can u show your controller method for login? – VeenarM Jun 16 '14 at 10:21
  • @VeenarM I changed the login.jsp to login.xhtml, still it does not work. Regarding the h prefix, the page renders properly!. – LalakaJ Jun 16 '14 at 10:31
  • @VeenarM I thought of using JPA but wanted to try tomcat's built in authentication. the controller method for the login is standard j_security_check. I didn't explicitly specify a controller to handle logins. – LalakaJ Jun 16 '14 at 10:35
  • Except it isn't tomcats built in authenticaiton, its JEE built in authentication. in which HttpServletRequest request = (HttpServletRequest) externalContext.getRequest(); request.login(email, user.getPassword()); I'm guessing this is similar? – VeenarM Jun 16 '14 at 10:38
  • I am using tomcat's realm configuration like specified here http://tomcat.apache.org/tomcat-7.0-doc/realm-howto.html. I get what you say, but when I specify the action of the form isn't tomcat supposed to access the database and check the username, password and roles and return me to the page which I was going to access.? – LalakaJ Jun 16 '14 at 10:44
  • I am using tomcat's realm configuration like specified here tomcat.apache.org/tomcat-7.0-doc/realm-howto.html. I get what you say, but when I specify the action of the form to j_security_check isn't tomcat supposed to access the database and check the username, password and roles and return me to the page which I was going to access, if my credentials are OK? That's what the server.xml file specifies a realm for isn't it? – LalakaJ Jun 16 '14 at 10:51
  • 1
    in server.xml it should be Context instead of context and put inside the Host element. Also, you should not define your contexts in server.xml, they belong in /conf/Catalina/localhost/.xml. – Cédric Couralet Jun 17 '14 at 09:29
  • @CédricC Thanks, I followed the instructions and added it to the given folder. I get it if you have multiple applications it is mixing up the realms. But why doesn't the tomcat documentation refer to the server.xml file in conf diretory? May be they should update it. And also the lowercase 'c' in context worked ;). the error was in server.xml's "userRolesTable" it should be "userRoleTable" – LalakaJ Jun 17 '14 at 10:52
  • @CédricC OK! Got it here http://tomcat.apache.org/tomcat-7.0-doc/config/context.html#Defining_a_context[link](http://tomcat.apache.org/tomcat-7.0-doc/config/context.html#Defining_a_context) – LalakaJ Jun 17 '14 at 10:56

1 Answers1

1

the error was in server.xml's "userRolesTable" it should be "userRoleTable"

LalakaJ
  • 531
  • 7
  • 16