loging not working in Spring security database integeration with encrypted password - spring

I have made one application where i have used spring security database driven and password as encrypted. but it is not working. if i configure user credential into xml file as encrypted password it works fine. Please help if anybody know the solution.
I have encoded password using org.springframework.security.authentication.encoding.ShaPasswordEncoder.encodePassword("password",null);
Please, Replay if anyone know the solution. Thank you.
Here is my applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.0.xsd">
<!-- ADD PERSISTENCE SUPPORT HERE (jpa, hibernate, etc) -->
<bean class="org.apache.commons.dbcp.BasicDataSource" id="dataSource" destroy-method="close" >
<property name="driverClassName">
<value>com.microsoft.sqlserver.jdbc.SQLServerDriver</value>
</property>
<property name="url">
<value>jdbc:sqlserver://192.162.101.111;databaseName=test</value>
</property>
<property name="username">
<value>root</value>
</property>
<property name="password">
<value>testroot</value>
</property>
<property name="maxActive" value="100"/>
<property name="maxWait" value="10000"/>
<property name="maxIdle" value="10"/>
</bean>
<!--- Spring security configuration --->
<security:http auto-config="true" >
<!-- Restrict URLs based on role -->
<security:intercept-url pattern="/POC/" access="IS_AUTHENTICATED_ANONYMOUSLY" />
<security:intercept-url pattern="/common/reportgenerator/**" access="IS_AUTHENTICATED_ANONYMOUSLY" />
<security:intercept-url pattern="/common/**" access="ROLE_BIDDER,ROLE_OFFICER" />
<security:intercept-url pattern="/bidder/**" access="ROLE_BIDDER" />
<security:intercept-url pattern="/officer/**" access="ROLE_OFFICER" />
<!-- Override default login and logout pages -->
<security:form-login login-page="/Login"
login-processing-url="/j_spring_security_check"
default-target-url="/"
always-use-default-target="true"
authentication-failure-url="/loginfailed" />
<security:logout logout-success-url="/logout" />
</security:http>
<security:authentication-manager>
<security:authentication-provider user-service-ref="" >
<security:user-service >
<security:user name="krupa#egp.com" password="c06d3569e5cb23eea69c8e264cbb43d817b95c2d" authorities="ROLE_OFFICER" />
</security:user-service>
<security:jdbc-user-service data-source-ref="dataSource"
users-by-username-query="select emailid username,lower(password) password,'true' enabled from tbl_LoginDetails where emailid=?"
authorities-by-username-query="select a.emailid username,b.authority from tbl_LoginDetails a,tbl_UserRoles b where a.userId=b.userId and a.emailid=?" />
<security:password-encoder ref="passwordEncoder" base64="false"/>
</security:authentication-provider>
</security:authentication-manager>
<bean id="passwordEncoder" class="org.springframework.security.authentication.encoding.ShaPasswordEncoder"></bean>
</beans>
The WEB.xml contains:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/</url-pattern>
</filter-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<listener>
<listener-class>
org.springframework.web.util.Log4jConfigListener
</listener-class>
</listener>
<!-- Spring Security filter entry -->
<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>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
<dispatcher>INCLUDE</dispatcher>
</filter-mapping>
</web-app>
Controller Details:
package com.abc.controller;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
#Controller
#RequestMapping("/")
public class HomeController
{
private static Logger logger = Logger.getLogger("controller");
#RequestMapping
public String showHome(ModelMap model) {
logger.debug("this is a sample log message.");
if(SecurityContextHolder.getContext().getAuthentication().isAuthenticated() && !SecurityContextHolder.getContext().getAuthentication().getPrincipal().toString().equalsIgnoreCase("anonymousUser"))
{
User user = null;
user=(User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
System.out.println(SecurityContextHolder.getContext().getAuthentication().getCredentials());
if(user !=null )
{
String name = user.getUsername();
model.addAttribute("username", name);
}
}
return "home";
}
#RequestMapping(value="/loginfailed", method = RequestMethod.GET)
public String loginerror(ModelMap model) {
logger.debug("login failed");
model.addAttribute("error", "true");
return "login";
}
#RequestMapping(value="/logout")
public String logout(ModelMap model) {
logger.debug("log out");
return "login";
}
#RequestMapping(value="/bidder/dashboard")
public String bidderDashboard(ModelMap model) {
return "bidder/dashboard";
}
#RequestMapping(value="/officer/dashboard")
public String officerDashboard(ModelMap model) {
return "officer/dashboard";
}
}
My Login Jsp Page is as per bellow:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<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 </h3>
<c:if test="${not empty error}">
<div class="errorblock">
Your login attempt was not successful, try again.<br /> Caused :<spring:message code="SPRING_SECURITY_LAST_EXCEPTION" text="Default Text" />
</div>
</c:if>
<form name='f' action="<c:url value='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>

Is that really the configuration file you are running with? It looks like there are a few problems with it and it
The syntax you have posted for <authentication-manager> is incorrect. You should have multiple authentication-provider elements in order to configure multiple user data sources to authenticate against. You only have one and the jdbc-user-service will probably be ignored in favour of the user-service element.
There is no password-encoder associated with the user-service element, so it won't work with encoded passwords, though you say it does. Are you sure?
Make sure that the value retrieved from the SQL query for the password exactly matches that calculated by the password encoder for the correct password (check it manually).
If none of these help, please provide a clearer explanation of what actually goes wrong. What doesn't work, and what version numbers are you using? Above all, what is the output of the debug log during a login? That is most likely to provide some pointers to what is happening.
Also, the web.xml, controller and login page are unlikely to be relevant for a password encoding issue (if you can log in successfully with one configuration but not another), so you can probably remove those.

I believe there are two things missing!
1. you cannot have two different elements in on . So either delete one of those or add another authentication-provider.
2. I cannot see where the password provided by the user is encrypted. You know, both passwords (the one in database, and the other which user gives) should be encrypted and be the same.

Related

spring can not send css & js resources

I use spring mvc and spring security for web app and tomcat as web application. I use mvc:resources to handle resources requests. But chrome console display following error:
Failed to load resource: the server responded with a status of 404 ()
Refused to execute script from 'http://localhost:8080/web-resources/jquery.min.js' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
:8080/favicon.ico Failed to load resource: the server responded with a status of 404 ()
This picture is my project structure:
My web.xml is:
<?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"
version="3.0">
<display-name>Archetype Created Web Application</display-name>
<welcome-file-list>
<welcome-file>login.jsp</welcome-file>
</welcome-file-list>
<!-- security config-->
<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>
<servlet>
<servlet-name>spring-mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring-mvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring-mvc-servlet.xml
/WEB-INF/security.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<page-encoding>UTF-8</page-encoding>
</jsp-property-group>
</jsp-config>
</web-app>
And my spring-mvc-servlet.xml is:
<?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" xmlns:mvc="http://www.springframework.org/schema/mvc"
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 http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:annotation-config/>
<context:component-scan base-package="java"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"/>
<property name="suffix" value=".jsp"/>
</bean>
<mvc:annotation-driven/>
<mvc:resources mapping="/web-resources/**" location="/web-resources" cache-period="31556926"/>
<mvc:resources mapping="/favicon.ico" location="/web-resources" cache-period="31556926"/>
</beans>
And security.xml is:
<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.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">
<http auto-config="true">
<intercept-url pattern="/user**" access="ROLE_USER"/>
<intercept-url pattern="/" access="permitAll"/>
<intercept-url pattern="/web-resources**" access="permitAll"/>
<form-login
login-page="/login"
default-target-url="/user/index"
authentication-failure-url="/login?error"
username-parameter="username"
password-parameter="password"/>
<logout logout-success-url="/login?logout"/>
<!-- enable csrf protection -->
<csrf/>
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="abcd" password="123456" authorities="ROLE_USER"/>
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
The following is view jsp file:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%# taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<html>
<body>
<h1 id="banner">Login to Security Demo</h1>
<form name="f" action="<c:url value='j_spring_security_check'/>"
method="POST">
<table>
<tr>
<td>Username:</td>
<td><input type='text' name='j_username'/></td>
</tr>
<tr>
<td>Password:</td>
<td><input type='password' name='j_password'></td>
</tr>
<tr>
<td colspan="2"> </td>
</tr>
<tr>
<td colspan='2'><input name="submit" type="submit"> <input name="reset" type="reset"></td>
</tr>
</table>
</form>
<script type="text/javascript" src="web-resources/jquery.min.js"></script>
</body>
</html>
your mvc resource mapping seems not set correct.
Try to change
<mvc:resources mapping="/web-resources/**" location="/web-resources" cache-period="31556926"/>
to
<mvc:resources mapping="/web-resources/**" location="/web-resources/" cache-period="31556926"/>
and also add following code to your spring security xml:
<http pattern="/web-resources/**" security="none"/>

Unable to access links that are mapped in admin Controller even after successful authentication and it is showing 404 error

I am working on a E commerce project in which I use spring security for authentication of users. Actually the project is working fine but when I login as an admin, it show me that I am successful authentication as admin and when I click on the links whose request mapping is in admin controller it show me 404 error ,page is unable to find.
WEB.XML
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID">
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/dispatcher-servlet.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- SPRING SECURITY CONFUGRATION -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring-security.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
</listener>
<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>
spring-security.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">
<context:component-scan base-package="com.**" />
<security:http auto-config="true" >
<security:intercept-url pattern="/webapp/resources/**" access="permitAll"/>
<security:intercept-url pattern="/login" access="permitAll"/>
<security:intercept-url pattern="/admin/**" access="hasRole('ROLE_ADMIN')"/>
<security:intercept-url pattern="/user/**" access="permitAll"/>
<security:form-login
login-page="/login"
username-parameter="username"
password-parameter="password"
authentication-success-forward-url="/userLogged"/>
<security:access-denied-handler
error-page="/error"/>
<security:csrf disabled="true"/>
<security:logout
logout-url="/logout"
invalidate-session="true"
logout-success-url="/" />
</security:http>
<security:authentication-manager>
<security:authentication-provider>
<security:jdbc-user-service
data-source-ref="dataSource"
users-by-username-query="select email, password, 'TRUE' as enabled from user where email=?"
authorities-by-username-query="select email, role from user where email=?"
/>
</security:authentication-provider>
</security:authentication-manager>
Admin Controller
#RequestMapping("/admin")
#Controller
public class adminController {
#RequestMapping("/insert")
public ModelAndView insertPage(){
ModelAndView mav =new ModelAndView("insert");
return mav;
}
}
Login Page
<form id="form" action="${pageContext.request.contextPath}/login" method="post" class="modal-content animate">
<div class="imgcontainer">
<img src="<c:url value="/resources/img/profile.png"/>"
alt="Avatar" class="avatar">
</div>
<div class="formcontainer">
<label><b>Username</b></label> <input type="text"
placeholder="Enter Username" name="username" required> <label><b>Password</b></label>
<input type="password" placeholder="Enter Password"
name="password" required>
<button type="submit">Login</button>
<input type="checkbox" checked="checked"> Remember me
</div>
<div class="formcontainer" style="background-color: #f1f1f1">
<button type="button"
onclick="document.getElementById('id01').style.display='none'"
class="cancelbtn">Cancel</button>
<span class="psw">Forgot password?</span>
</div>
</form>
Error screenshot

j-spring-security The requested resource is not available

i had created login authentication using the spring security framework..
when i include the <!-- Spring Security --> below entries in the web.xml the index page is not shown, also if i don't include the tag (<!-- Spring Security -->), the index page is shown, when i enter the userid/password and click on the submit button, i get the error
error without adding <!-- spring security --> tag
----------------------------------------------------
http://sgv09946224.gbl.ad.hedani.net:8080/SpringMVCExample/j_spring_security_check
HTTP Status 404 - The requested resource is not available.
error while adding <!-- spring security --> tag
----------------------------------------------------
http://sgv09946224.gbl.ad.hedani.net:8080/SpringMVCExample/
HTTP Status 404 - /SpringMVCExample/
type Status report
message /SpringMVCExample/
description The requested resource is not available.
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<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_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>SpringMVCExample</display-name>
<!--
- Location of the XML file that defines the root application context.
- Applied by ContextLoaderListener.
-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:spring/application-config.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--
- Servlet that dispatches request to registered handlers (Controller implementations).
-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-config.xml /WEB-INF/mvc-security.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- 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>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
</web-app>
mvc-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- Uncomment and your base-package here:
<context:component-scan
base-package="org.springframework.samples.web"/> -->
<mvc:resources mapping="/SpringMVCExample/resources/**" location="SpringMVCExample/resources/" />
<mvc:resources mapping="/images/**" location="/WEB-INF/images/" />
<mvc:annotation-driven />
<context:component-scan base-package="com.controller" />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- Example: a logical view name of 'showMessage' is mapped to '/WEB-INF/jsp/showMessage.jsp' -->
<property name="prefix" value="/WEB-INF/view/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
mvc-security.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<security:http auto-config="true">
<security:intercept-url pattern="/index*" access="ROLE_USER" />
<security:form-login login-page="/index" default-target-url="/showMessage"
authentication-failure-url="/fail2login" />
<security:logout logout-success-url="/logout" />
</security:http>
<security:authentication-manager>
<security:authentication-provider>
<security:user-service>
<security:user name="l1" password="l1" authorities="ROLE_USER" />
</security:user-service>
</security:authentication-provider>
</security:authentication-manager>
</beans>
index.jsp
<!DOCTYPE html>
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<html>
<head>
<meta charset="utf-8">
<title>Welcome</title>
</head>
<body>
<img src="/SpringMVCExample/images/SupportDashboard.jpg"/>
<c:if test="${not empty error}">
Your login attempt was not successful, try again
</c:if>
<form name='f' action="<c:url value='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>
<c:url value="/showMessage.html" var="messageUrl" />
Click to enter
</body>
</html>
showmessage.jsp
<!DOCTYPE html>
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<meta charset="utf-8">
<title>Welcome</title>
</head>
<body>
<h2>${message}</h2>
</body>
</html>
spring/application-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- Uncomment and add your base-package here:
<context:component-scan
base-package="org.springframework.samples.service"/> -->
<!-- hibernate configuration and mappings
<import resource="mvc-security.xml"/> -->
</beans>
maincontroller.java
package com.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.validation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.ui.ModelMap;
/*
* author: Crunchify.com
*
*/
#Controller
public class MainController {
#RequestMapping("/showMessage")
public ModelAndView helloWorld() {
System.out.println("inisde showmessage method");
String message = "<br><div style='text-align:center;'>" +
"<h3>********** Welcome to LDO Support Landing page **********<h3> </div><br><br>";
return new ModelAndView("showMessage", "message", message);
}
#RequestMapping("/index")
public ModelAndView index() {
System.out.println("inisde index method");
String message = "<br><div style='text-align:center;'>" +
"<h3>********** Welcome to LDO Support Landing page **********<h3> </div><br><br>";
return new ModelAndView("showMessage", "message", message);
}
#RequestMapping(value="/fail2login", method = RequestMethod.GET)
public String loginerror(ModelMap model) {
System.out.println("inisde fail2login method");
model.addAttribute("error", "true");
return "login";
}
#RequestMapping(value="/logout", method = RequestMethod.GET)
public String logout(ModelMap model) {
System.out.println("inisde logout method");
return "login";
}
}
modified web.xml which worked for me
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/mvc-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</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-*.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>

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

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
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://testcebs.com: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.
You've been answered here and here, please don't cross-post
The answers:
if the j_spring_security_check URL is not part of the HST driven then make sure you add it to you hst:hosts exclusions, because otherwise the HST thinks it needs to handle the URL.
and
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; http://hst-springsec.forge.onehippo.org/

Spring Security Method Security Annotations

Recently, I have begun a bit of a personal project, and I decided to implement Spring Security. I have attempted to do so before, but I had no better luck that time than I am now. I got around the problem then, but that method (accessing the security context directly from the code and checking the string of roles it contains for the current user) feels like a hack, and I would like to get it right this time.
Right now I have Spring Security MOSTLY functioning, as far as I know...I can attempt to go to a page with a role-based redirect, and it will redirect me to the login page. I can log in with good or bad information and be sent to the proper location. What I cannot do, what I have never managed to do, is get the #Secured or #PreAuthorize annotation to function as I would hope.
Let me try to explain (code will follow). My welcome/login page is index.jsp and, when you log in, Spring Security sends you to login.html which is where I have a method in my LoginController class mapped. Inside that method, I try to call a large set of other methods: none of this is supposed to be final, I am just trying to get prove to myself that things are running.
I call two methods that are secured by #Secured, and two methods that are secured by #PreAuthorize, one "ROLE_ADMIN" and one "ROLE_USER" each. The account that I am logging into only has the ROLE_USER authority. This being the case, I would expect to get redirected to my accessdenied.jsp page as per having set that as the target of my Spring Security's access-denied-page attribute. What I do not expect, and what I am seeing, is that every method is successfully called and run when I log in.
I have (at least attempted to) follow the tutorials. I have spent days on Google, reading everything that I can find. I have merged my security context into my context, and everything else that came to my attention as a potential solution. I apologize if I have been a mite long-winded, but I would rather provide too much information than too little. To that end, the following is my code:
index.jsp
<html>
<body>
<form action="j_spring_security_check" method="POST">
<label for="j_username">Name:</label>
<input id="j_username" type='text' name='j_username' />
<br />
<label for="j_password" class="passwordField">Password:</label>
<input id="j_password" type='password' name='j_password' />
<br />
<input id="proceed" type="submit" value="Submit" />
</form>
</body>
</html>
LoginController.java
package cribbage.controller;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.annotation.Secured;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.jdbc.core.JdbcTemplate;
import cribbage.database.entity.Test;
#Controller
public class LoginController {
#Autowired
JdbcTemplate t;
#RequestMapping(value = "/login")
public ModelAndView login(HttpServletRequest request) {
test();
test2();
test3();
test4();
return new ModelAndView("test.jsp");
}
#Secured("ROLE_ADMIN")
public void test(){
System.out.println("Test One");
}
#Secured("ROLE_USER")
public void test2(){
System.out.println("Test Two");
}
#PreAuthorize("hasRole('ROLE_ADMIN')")
public void test3(){
System.out.println("Test Three");
}
#PreAuthorize("hasRole('ROLE_USER')")
public void test4(){
System.out.println("Test Four");
}
}
web.xml
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<display-name>Spring Security Tutorial Application</display-name>
<!-- - Location of the XML file that defines the root application context
- Applied by ContextLoaderListener. -->
<context-param>
<description>Spring context file</description>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext.xml
/WEB-INF/applicationContext-security.xml
</param-value>
</context-param>
<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>
<!-- - Provides core MVC application controller. See bank-servlet.xml. -->
<servlet>
<servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext.xml
/WEB-INF/applicationContext-security.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<context:property-placeholder location="classpath:*.properties" />
<mvc:annotation-driven />
<!-- Which packages to scan when looking for beans defined with #Component -->
<context:component-scan scoped-proxy="targetClass"
base-package="cribbage.controller
cribbage.database.dao
cribbage.database.entity" />
<context:annotation-config />
<!-- Turn on AspectJ #Configurable support -->
<!-- Turn on #Autowired, #PostConstruct etc support -->
<bean
class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
<bean
class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor" />
<!-- Add Transaction support -->
<!-- Use #Transaction annotations for managing transactions -->
<tx:annotation-driven transaction-manager="txManager" />
<bean id="txManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource" />
<bean id="localeResolver"
class="org.springframework.web.servlet.i18n.SessionLocaleResolver"
p:defaultLocale="en_US" />
<!-- For database, uses maven filtering to fill in place holders -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${db.driver}" />
<property name="url" value="${db.url}" />
<property name="username" value="${db.username}" />
<property name="password" value="${db.password}" />
<property name="maxActive" value="10" />
<property name="maxIdle" value="1" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<constructor-arg ref="dataSource" />
</bean>
<security:global-method-security
secured-annotations="enabled" pre-post-annotations="enabled" />
applicationContext-security.xml
<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.1.xsd">
<http pattern="/CSS/**" security="none" />
<http auto-config="true" use-expressions="true" access-denied-page="/accessdenied.jsp">
<form-login always-use-default-target="false"
login-processing-url="/j_spring_security_check" default-target-url="/login.html"
login-page="/index.jsp" authentication-failure-url="/loginFailed.jsp" />
<logout logout-url="/j_spring_security_logout" />
<intercept-url pattern="/test.jsp" access="hasRole('ROLE_USER')" />
</http>
<authentication-manager>
<authentication-provider>
<jdbc-user-service data-source-ref="dataSource"
users-by-username-query="select username,user_password,enabled from users where username=?"
authorities-by-username-query="select username,authority,enabled from users where username=?" />
</authentication-provider>
</authentication-manager>
Thank you for any help that you can provide.
actully spring security works only if aspect/security interceptor involved. In your code test(),test2(),test3(),test4() are invoked directly from controller method login. so there will not be any aspect involvement causing security to be bypassed.
if test methods are part of another spring bean then this should work as you have been expecting.
or if they are in same class then it should be invoked with spring bean instead of this (current object).

Resources