Spring WebFlow + Spring Security + File multipart upload - spring

help me please, i can't solve problem for 2 days:
Here is a flow
"create-magazine.xml"
<view-state id="createMagazineForm" view="createmagazine" model="magazine">
<transition on="submit" to="createMagazineAction" />
</view-state>
<action-state id="createMagazineAction">
<evaluate expression="createMagazineService.justTest(magazine,flowRequestContext)" />
<transition on="success" to="createMagazineSuccess"/>
</action-state>
<view-state id="createMagazineSuccess" view="createsuccess" >
</view-state>
Here is createmagazine.jsp:
<form:form method="POST" modelAttribute="magazine" enctype="multipart/form-data">
<div class="form-group">
<fieldset>
<p>Your title</p>
<form:input placeholder="Title here" cssClass="form-control" path="vtitle" />
<p>Magazine image</p>
<input type="file" class="form-control" name="vimage" />
</fieldset>
<input type="hidden" name="${_csrf.parameterName}"
value="${_csrf.token}" />
<input type="submit" class="btn btn-success" value="Create" name="_eventId_submit" />
</div>
</form:form>
And createsuccess.jsp:
<h1 class="jumbotron">Magazine created</h1>
<p>${magazine.vtitle}</p>
<p>${magazine.vimage.getName()}</p>
Here is my model object:
#XmlRootElement
public class Magazine implements Serializable{
private Integer id;
private String vtitle;
private MultipartFile vimage;
public Integer getId() {
return id;
}
public MultipartFile getVimage() {
return vimage;
}
public void setVimage(MultipartFile vimage) {
this.vimage = vimage;
}
public void setId(Integer id) {
this.id = id;
}
public String getVtitle() {
return vtitle;
}
public void setVtitle(String vtitle) {
this.vtitle = vtitle;
}
}
After clicking submit button I get 405 Request method 'POST' not supported
I think it's because of Spring Security
Update : Here is my security-config
<!-- enable use-expressions -->
<http auto-config="true" use-expressions="true">
<intercept-url pattern="/admin**" access="hasRole('Admin')" />
<intercept-url pattern="/secured**" access="hasRole('User')" />
<!-- access denied page -->
<access-denied-handler error-page="/403" />
<form-login
login-page="/login"
default-target-url="/secured"
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-ref="myUserDetailsService" >
<password-encoder hash="bcrypt" />
</authentication-provider>
</authentication-manager>

Thanks #M. Deinum
I solved the problem. First I fixed web.xml:
<!-- Spring MVC -->
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/dispatcher-servlet.xml
/WEB-INF/spring/webflow-config.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
<multipart-config>
<location>/tmp</location>
<max-file-size>20848820000</max-file-size>
<max-request-size>41801884100</max-request-size>
<file-size-threshold>104857600</file-size-threshold>
</multipart-config>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- Spring Security -->
<filter>
<filter-name>csrfFilter</filter-name>
<filter-class>
org.springframework.web.filter.DelegatingFilterProxy
</filter-class>
<async-supported>true</async-supported>
</filter>
<filter-mapping>
<filter-name>csrfFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter>
<description>
Allows the application to accept multipart file data.
</description>
<display-name>springMultipartFilter</display-name>
<filter-name>springMultipartFilter</filter-name>
<filter-class>
org.springframework.web.multipart.support.MultipartFilter</filter-class>
<!--init-param>
<param-name>multipartResolverBeanName</param-name>
<param-value>multipartResolver</param-value>
</init-param-->
</filter>
<filter>
<description>
Secures access to web resources using the Spring Security framework.
</description>
<display-name>springSecurityFilterChain</display-name>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy
</filter-class>
</filter>
<filter-mapping>
<filter-name>springMultipartFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>ERROR</dispatcher>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
Then I changed my method to:
public String justTest(Magazine magazine,RequestContext requestContext){
ServletExternalContext context = (ServletExternalContext) requestContext.getExternalContext();
MultipartHttpServletRequest multipartRequest = new StandardMultipartHttpServletRequest((HttpServletRequest)context.getNativeRequest());
magazine.setFile(multipartRequest.getFile("file"));
requestContext.getFlowScope().put("magazine", magazine);
return "success";
}

Related

jsf commandButton managedBean action redirect to 404 page

I have my ManagedBean
TodoService.java
package com.medkhelifi.tutorials.todolist.services;
import com.medkhelifi.tutorials.todolist.models.dao.ITodoDao;
import com.medkhelifi.tutorials.todolist.models.entities.Todo;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.bean.SessionScoped;
#ManagedBean
#RequestScoped
public class TodoService implements ITodoService {
#ManagedProperty(value = "ITodoDao")
private ITodoDao ITodoDao;
#Override
public void addTodo(Todo todo) {
ITodoDao.addTodo(todo);
}
public void setITodoDao(ITodoDao ITodoDao) {
this.ITodoDao = ITodoDao;
}
}
And I have my form to add new data
index.xhtml
<!-- extra code coes here -->
<b:column colMd="6">
<div class="todolist not-done">
<h1>Todos</h1>
<h:form>
<b:inputText type="text" class="form-control add-todo" placeholder="Todo Title"/>
<b:inputTextarea type="text" placeholder="Description" />
<b:dateTimePicker placeholder="todo Date" format="YYYY-MM-DD HH:mm:ss"/>
<h:commandButton action="#{todoService.addTodo(null)}" class="btn btn-success" value="Add"/>
</h:form>
<hr/>
<ul class="list-unstyled" >
<ui:repeat value="#{TodoDao.getCurrentUserTodos()}" var="todo" >
<h:panelGroup rendered="#{!todo.done}">
<li class="ui-state-default">
<div class="checkbox">
<label><input type="checkbox" value="" />#{todo.title}</label>
</div>
</li>
</h:panelGroup>
</ui:repeat>
</ul>
<div class="todo-footer">
<strong><span class="count-todos"/></strong> Items Left
</div>
</div>
</b:column>
<!-- extra code coes here -->
When I perform my add button I'm redirected to the same page with 404 status.
There is my web.xml
<?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">
<!-- DEFINE APPLICATION ENVIRONMENT -->
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<!-- DEFINE JSF SERVLET MAPPING -->
<servlet>
<servlet-name>FACES SERVLET</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>FACES SERVLET</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<!-- DEFINE WELCOME PAGE -->
<welcome-file-list>
<welcome-file>index.xhtml</welcome-file>
</welcome-file-list>
<!-- SPRING SERVLETS -->
<servlet>
<servlet-name>dispatcher-servlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/conf/applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher-servlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- SPRING CONTEXT -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:conf/applicationContext.xml</param-value>
</context-param>
<!-- SPRING SECURITY FILTER -->
<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>
<!-- Add this dispatcher to handle /j_spring_security_check url -->
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
</web-app>
I use also Spring security:
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-4.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-4.0.xsd">
<http auto-config="true">
<intercept-url pattern="/login*" access="permitAll()"/>
<intercept-url pattern="/javax.faces.resource/**" access="permitAll()"/>
<intercept-url pattern="/**" access="isAuthenticated()" />
<!-- access denied page -->
<access-denied-handler error-page="/403" />
<form-login
login-page="/login.xhtml"
default-target-url="/index.xhtml"
authentication-failure-url="/login.xhtml?error"
login-processing-url="/j_spring_security_check"
username-parameter="input_username"
password-parameter="input_password" />
<logout
logout-success-url="/login.xhtml"
/>
<!-- enable csrf protection -->
<csrf />
</http>
<authentication-manager>
<authentication-provider user-service-ref="myUserDetailsService">
<password-encoder hash="bcrypt"/>
</authentication-provider>
</authentication-manager>
</beans:beans>
And when I debug, the method TodoService.addTodo is never called, I hope I explained my problem well.
There is my stack:
Spring 4.2.2-Final
JSF 2.2.17
After few hours of searching I found the issue:
I missed to add csrf security hidden input to my form since I use csrf protection in my Spring security.
index.xhtml
<!-- extra code coes here -->
<b:column colMd="6">
<div class="todolist not-done">
<h1>Todos</h1>
<h:form>
<b:inputText type="text" class="form-control add-todo" placeholder="Todo Title"/>
<b:inputTextarea type="text" placeholder="Description" />
<b:dateTimePicker placeholder="todo Date" format="YYYY-MM-DD HH:mm:ss"/>
<!-- I missed to add this line -->
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
<h:commandButton action="#{todoService.addTodo(null)}" class="btn btn-success" value="Add"/>
</h:form>
<hr/>
<ul class="list-unstyled" >
<ui:repeat value="#{TodoDao.getCurrentUserTodos()}" var="todo" >
<h:panelGroup rendered="#{!todo.done}">
<li class="ui-state-default">
<div class="checkbox">
<label><input type="checkbox" value="" />#{todo.title}</label>
</div>
</li>
</h:panelGroup>
</ui:repeat>
</ul>
<div class="todo-footer">
<strong><span class="count-todos"/></strong> Items Left
</div>
</div>
</b:column>
<!-- extra code coes here -->

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

Spring MVC and Security - Error 404 page not found after login

I need some help with this Spring test project. I have a simple log in page with security check, Spring detect good or bed login but gives 404 Page not fount error when redirect into login-succes page or login-faild page.
Configurations are
APPLCATION CONTEXT
<!--
Most controllers will use the ControllerClassNameHandlerMapping above, but
for the index controller we are using ParameterizableViewController, so we must
define an explicit mapping for it.
-->
<bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="login.htm">LoginController</prop>
</props>
</property>
</bean>
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/"
p:suffix=".jsp" />
<!--
The index controller.
-->
<bean name="LoginController"
class="org.springframework.web.servlet.mvc.ParameterizableViewController"
p:viewName="login" />
</beans>
SECURITY
<http auto-config="true">
<intercept-url pattern="/welcome*" access="ROLE_USER" />
<form-login login-page="/login" default-target-url="/welcome"
authentication-failure-url="/loginfailed" />
<logout logout-success-url="/logout" />
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="mkyong" password="123456" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
WEB.XML
<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>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/dispatcher-servlet.xml,
/WEB-INF/spring-security.xml
</param-value>
</context-param>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>redirect.jsp</welcome-file>
</welcome-file-list>
<!-- 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>
The login controller is
#Controller
public class LoginController {
#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) {
return "login";
}
#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";
}
}
Where is the error? TK.

loging not working in Spring security database integeration with encrypted password

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.

spring security not working

I am developing a struts2 + spring + tiles + hibernate + spring security application
When I go to url /register I am correctly redirected to the login page,
but on logging in with username and password specified in the bean configuration file,
I am redirected back to the login page with url "login?error=true" which means that the login was unsuccessful as I have mentioned "authentication-failure-url="/login?error=true""
I have configured form based login with the following configuration
//web.xml
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext.xml
/WEB-INF/medic-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>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
//medics-security.xml
<http auto-config="true" access-denied-page="/error">
<intercept-url pattern="/" access="IS_AUTHENTICATED_ANONYMOUSLY"/>
<intercept-url pattern="/register*" access="ROLE_USER" />
<intercept-url pattern="/messagePost*" access="ROLE_USER" />
<intercept-url pattern="/messageDelete*" access="ROLE_ADMIN" />
<form-login login-page="/login" authentication-failure-url="/login?error=true"/>
<remember-me/>
<logout/>
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="admin" password="secret" authorities="ROLE_USER"/>
</user-service>
</authentication-provider>
</authentication-manager>
//login.jsp
<form action="j_spring_security_check">
<label for="j_username">Username</label>
<input type="text" name="j_username" id="j_username"/><br/>
<label for="j_password">Password</label>
<input type="password" name="j_password" id="j_password"/><br/>
<input type='checkbox' name='_spring_security_remember_me'/> Remember me<br/>
<input type="submit" value="Login"/>
<input type="reset" value="Reset"/>
</form>
//struts.xml
<package name="default" namespace="/" extends="struts-default">
<action name="login" class="com.medics.action.LoginAction">
<result name="SUCCESS" type="tiles">login</result>
</action>
<action name="register" class="com.medics.action.RegisterAction">
<result name="SUCCESS">/Register.jsp</result>
</action>
</package>
Action classes are doing nothing except returning "SUCCESS"
Since you have not specified a method for <form>, it uses GET, which is the default. spring-security 3.x does not allow authentication using GET, by default.
Can you try adding method="post" and see if that helps?

Resources