Login page with Spring Security not working URL(http://localhost:8080/site/j_spring_security_check) goes to PAGE NOT FOUND

2,022 views
Skip to first unread message

i.tpr...@gmail.com

unread,
Jul 16, 2013, 9:50:40 AM7/16/13
to hippo-c...@googlegroups.com
 Hello Hippo,

I am new to hippo and working on hippo cms site.
I am working on creating a login page with spring security. For this I created the following files and did the configuration for spring and spring security.


Here is my Login.jsp.


<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>Login Page</title>
<style>
.errorblock {
    color: #ff0000;
    background-color: #ffEEEE;
    border: 3px solid #ff0000;
    padding: 8px;
    margin: 16px;
}
</style>
</head>
<body onload='document.f.j_username.focus();'>
    <h3>Login with Username and Password (Custom Page)</h3>

    <c:if test="${not empty error}">
        <div class="errorblock">
            Your login attempt was not successful, try again.<br /> Caused :
            ${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message}
        </div>
    </c:if>

    <form name='f' action="/j_spring_security_check"
        method='POST'>

        <table>
            <tr>
                <td>User:</td>
                <td><input type='text' name='j_username' value=''>
                </td>
            </tr>
            <tr>
                <td>Password:</td>
                <td><input type='password' name='j_password' />
                </td>
            </tr>
            <tr>
                <td colspan='2'><input name="submit" type="submit"
                    value="submit" />
                </td>
            </tr>
            <tr>
                <td colspan='2'><input name="reset" type="reset" />
                </td>
            </tr>
        </table>

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


The configuration files.

1) Web.xml configuration


<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
    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">

    <display-name>Spring MVC Application</display-name>

    <!-- Spring MVC -->
    <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/mvc-dispatcher-servlet.xml,
            /WEB-INF/spring-database.xml,
            /WEB-INF/spring-security.xml
        </param-value>
    </context-param>

    <!-- Spring Security -->
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

2) mvc-dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans   
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:component-scan base-package="com.example.common.controller" />

    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/pages/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>

    <bean id="messageSource"
        class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basenames">
            <list>
                <value>mymessages</value>
            </list>
        </property>
    </bean>
  
</beans>

3) spring-database.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/vnp_db" />
        <property name="username" value="root" />
        <property name="password" value="admin" />
    </bean>

</beans>


4) spring-security.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/security
    http://www.springframework.org/schema/security/spring-security-3.0.xsd">

    <http auto-config="true">
        <intercept-url pattern="/welcome*" access="ROLE_USER" />
        <form-login login-page="/login" default-target-url="/welcome"
            authentication-failure-url="/loginfailed"  login-processing-url="/j_spring_security_check"/>
        <logout logout-success-url="/logout" />
    </http>

    <authentication-manager>
        <authentication-provider>
          <jdbc-user-service data-source-ref="dataSource"
              
                users-by-username-query="
                    select email,password, enabled
                    from users where email=?"
              
                authorities-by-username-query="
                    select u.email, ur.authority from users u, authorities ur
                    where u.email = ur.email and u.email =?  "
            />
        </authentication-provider>
    </authentication-manager>

</beans:beans>

And the controller file


5) LoginController.java

package org.vnp.common.controller;

import java.security.Principal;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;


@Controller
public class LoginController {
  
      @RequestMapping(value = "/home", method = RequestMethod.GET)
        public String home() {
           return "home";
        }
  
  
    @RequestMapping(value="/welcome", method = RequestMethod.GET)
    public String printWelcome(ModelMap model, Principal principal ) {
 
        String name = principal.getName();
        model.addAttribute("username", name);
        model.addAttribute("message", "Spring Security Custom Form example");
        return "hello";
 
    }
 
    @RequestMapping(value="/login", method = RequestMethod.GET)
    public String login(ModelMap model) {
        String goToPage;
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (!(auth instanceof AnonymousAuthenticationToken)) {
            /*The user is logged in :)*/
            goToPage = "welcome";
            }
        else{
            goToPage = "login";
        }
        return goToPage;
 
    }
  
    @RequestMapping(value="/loginfailed", method = RequestMethod.GET)
    public String loginerror(ModelMap model) {
 
        model.addAttribute("error", "true");
        return "login";
 
    }
  
    @RequestMapping(value="/logout", method = RequestMethod.GET)
    public String logout(ModelMap model) {
 
        return "login";
 
    }
  
    @RequestMapping(value = "/finalPage", method = RequestMethod.GET)
    public String finalPage() {
    
       return "final";
    }
  
    @RequestMapping(value = "/register", method = RequestMethod.GET)
       public ModelAndView register() {
          return new ModelAndView("registeruser", "command", new UserModel());
       }
    /**
     *
     * @param user
     * @param model
     * @return
     *
     * <br/><br/>
     * This method is for adding user.
     */
    @RequestMapping(value = "/addUser", method = RequestMethod.POST)
       public String addUser(@ModelAttribute("SpringWeb")UserModel user,
       ModelMap model) {
      
        System.out.println("Here adding userL:-----");
      
          //model.addAttribute("id", user.getId());
          model.addAttribute("username", user.getUsername());
          model.addAttribute("email", user.getEmail());
          model.addAttribute("password", user.getPassword());
          model.addAttribute("enabled", user.isEnabled());
          model.addAttribute("creationDate", user.getCreationDate());
         /* ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
          HibernateTemplate ht=(HibernateTemplate) context.getBean("hibernateTemplate");
          ht.saveOrUpdate(user);*/
          try{
              System.out.println("Going to load driver");
              Class.forName("com.mysql.jdbc.Driver");
              System.out.println("Driver loaded getting connection");
              Connection  conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/vnp_db","root", "admin");
              System.out.println("connection got preparing statement");
              PreparedStatement ps = conn.prepareStatement("insert into users(username,email,password,creation_date,enabled) values(?,?,?,?,?)");
              System.out.println("query prepared");
              ps.setString(1, user.getUsername());
              ps.setString(2, user.getEmail());
              ps.setString(3, user.getPassword());
              ps.setDate(4, new Date(System.currentTimeMillis()));
              ps.setBoolean(5, user.isEnabled());
              System.out.println("executing 1111");
              int a = ps.executeUpdate();
              System.out.println("user created");
              if(a>0)
              {
                  System.out.println("secong statement prepared");
                  PreparedStatement ps1 = conn.prepareStatement("insert into authorities values(?,?)");
                  ps1.setString(1, user.getEmail());
                  ps1.setString(2, "ROLE_USER");
                  int x = ps1.executeUpdate();
                  System.out.println("authorities assigned"+x);
              }
            
          }catch (Exception e) {

              System.out.println("Exception creating user"+e.getLocalizedMessage());
              e.printStackTrace();
        
          }
        
      
          return "login";
       }

}


This module also contains registration part using spring thar part is working fine . On the login page I fill the
correct username and password and clicks "Login" button. The url goes to "http://localhost:8080/site/j_spring_security_check"

and redirects to PAGE NOT FOUND instead of success and fail.No authentication process initatied after clicking on "Login" button.

I am not able to understand why it is not working

However the same code and configuration is working fine in eclipse as a spring application.

Please help me to get this working.

Regards,
Pranav



Adolfo Benedetti

unread,
Jul 16, 2013, 10:04:10 AM7/16/13
to hippo-c...@googlegroups.com
Hi Pranav,

You need to insert
​ the​
SpringSecurityValve into your existing pipelines
​ as well​
.
​you can use the
 hippo-spring-sec
​ plugin for a cleaner spring security integration;
​cheers,

Adolfo​


--
Adolfo Benedetti



2013/7/16 <i.tpr...@gmail.com>
--
Hippo Community Group: The place for all discussions and announcements about Hippo CMS (and HST, repository etc. etc.)
Most Hippo developers are active here and/or follow the Stackoverflow [hippo-cms] tag.
 
The old Nabble archive can be found here: http://hippo.2275632.n2.nabble.com/Hippo-CMS-7-f2274273.html
 
To post to this group, send email to hippo-c...@googlegroups.com
RSS: https://groups.google.com/group/hippo-community/feed/rss_v2_0_msgs.xml?num=50
---
You received this message because you are subscribed to the Google Groups "Hippo Community" group.
To unsubscribe from this group and stop receiving emails from it, send an email to hippo-communi...@googlegroups.com.
Visit this group at http://groups.google.com/group/hippo-community.
For more options, visit https://groups.google.com/groups/opt_out.
 
 

Reply all
Reply to author
Forward
0 new messages