jsf commandButton managedBean action redirect to 404 page - spring

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 -->

Related

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

sec:authorize access="hasRole('ROLE_USER')" doesn't work

My menu.jspx doesn't work correctly. I can see both <sec:authorize access
<sec:authorize access="hasRole('ROLE_USER')">
<h3>${menuAddContact}</h3><!--будет отображатсья только если юзер зашел и нужной ролью-->
</sec:authorize>
<sec:authorize access="isAnonymous()"><!--Если не зашел то отбражается форма входа-->
<div id="login">
<form name="loginForm" action="${loginUrl}" method="post">
<table>
<caption align="left">Login:</caption>
<tr>
<td>User Name:</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" align="center"><input type="submit"
name="submit"
value="Login"/></td>
</tr>
</table>
</form>
</div>
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<div id="menu" xmlns:jsp="http://java.sun.com/JSP/Page"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:spring="http://www.springframework.org/tags"
xmlns:sec="http://www.springframework.org/security/tags"
version="2.0">
<jsp:directive.page contentType="text/html;charset=UTF-8" />
<jsp:output omit-xml-declaration="yes" />
<spring:message code="menu_header_text" var="menuHeaderText"/>
<spring:message code="menu_add_contact" var="menuAddContact"/>
<spring:url value="/contacts?form" var="addContactUrl"/>
<spring:message code="label_login" var="labelLogin"/>
<spring:url var="loginUrl" value="/j_spring_security_check"/>
<h3>${menuHeaderText}</h3>
<sec:authorize access="hasRole('ROLE_USER')">
<h3>${menuAddContact}</h3><!--будет отображатсья только если юзер зашел и нужной ролью-->
</sec:authorize>
<sec:authorize access="isAnonymous()"><!--Если не зашел то отбражается форма входа-->
<div id="login">
<form name="loginForm" action="${loginUrl}" method="post">
<table>
<caption align="left">Login:</caption>
<tr>
<td>User Name:</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" align="center"><input type="submit"
name="submit"
value="Login"/></td>
</tr>
</table>
</form>
</div>
</sec:authorize>
</div>
And in my header
<sec:authorize access="isAuthenticated()">${labelWelcome}
<sec:authentication property="principal.username" />
username does not exist(
It seems that spring security does not exist(
<?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.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">
<http use-expressions="true">
<intercept-url pattern='/WEB-INF' access='permitAll' />
<form-login login-page="/contacts" authentication-failure-url="/security/loginfail"
default-target-url="/contacts" />
<logout logout-success-url="/contacts"/>
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="user" password="user" authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
But, if i use F12 in my browser i can see that spring return form data correctly
j_username:user
j_password:user
submit:Login
help me please( where my mistake?
UPD:
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">
<display-name>java-blog-aggregator</display-name>
<context-param>
<param-name>spring.profiles.default</param-name>
<param-value>jdbc,mysql</param-value>
<!--<param-value>hibernate,mysql</param-value>-->
<!--<param-value>datajpa,mysql</param-value>-->
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<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</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<filter>
<filter-name>CharacterEncodingFilter</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>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<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>
root-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">
<import resource="classpath:spring/app-context.xml"/>
<import resource="classpath:spring/security-context.xml"/>
</beans>
I didn't add in pom.xml taglib dependency

Spring WebFlow + Spring Security + File multipart upload

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";
}

Spring security login crashes after the login page it shows the css , js, image files . How to fix this?

when i open the web application from browser.
localhost:8080/myapp
it shows the login page with out styled in the css file. even refresh also it shows normal form but we can give the login credentials to log into the application.
now the problem is it shows the js files i used in the my application
localhost:8080/myapp/some.js
now we remove the some.js file and hit the url now it shows the css file or js file. it happens in two to three times after re hit the url it shows the correct login form and goes to the dashbord.
how to fix this issue please help me out this problem.
security.xml file
<?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"
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">
<security:http auto-config="true">
<security:intercept-url pattern="/login" access="ROLE_ANONYMOUS"/>
<security:intercept-url pattern="/**" access="ROLE_USER,ROLE_ADMIN"/>
<security:intercept-url pattern="/admin/**" access="ROLE_ADMIN" />
<security:form-login
login-page="/login"
default-target-url="/default"
authentication-failure-url="/login?error"
username-parameter="username"
password-parameter="password" ></security:form-login>
<security:logout logout-success-url="/login?logout" />
</security:http>
<security:authentication-manager>
<security:authentication-provider>
<security:user-service>
<security:user name="user" password="123456" authorities="ROLE_USER" />
<security:user name="admin" password="password" authorities="ROLE_ADMIN" />
</security:user-service>
</security:authentication-provider>
</security:authentication-manager>
login.jsp file
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<link href="<c:url value="/resources/css/anchor.css"/>" rel="stylesheet"
type="text/css">
<link href="<c:url value="/resources/css/bootstrap.min.css"/>"
rel="stylesheet">
<div>
<form name='loginForm' class="form col-md-12 center-block"
action="<c:url value='j_spring_security_check' />" method='POST'>
<div id="loginModal" class="modal show" tabindex="-1" role="dialog"
aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h1 class="text-center">Login</h1>
<c:if test="${not empty error}">
<div class="error">${error}</div>
</c:if>
<c:if test="${not empty msg}">
<div class="msg">${msg}</div>
</c:if>
</div>
<div class="modal-body">
<div class="form-group">
<input type="text" name='username'
class="form-control input-lg"
placeholder="Username">
</div>
<div class="form-group">
<input type="password" name='password'
placeholder="Password">
</div>
<div class="form-group">
<button>Sign In</button>
</div>
<input type="hidden" name="${_csrf.parameterName}"
value="${_csrf.token}" />
<!-- </form> -->
</form>
</div>
</div>
</div>
please help me out this issue. all most myapp is finished the all modules now this time to deliver to customer, kindly please help me out this issue.
How to fix this when i login it redirects to the css or js or images resources files.
This is my web.xml file
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/root-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<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>
Kindly please help me out this issue
i suffred same problem like this
Why does my Spring Security login.jsp puke CSS and how do I fix it?
The problem is your security mapping at this line:
<security:intercept-url pattern="/**" access="ROLE_USER,ROLE_ADMIN"/>
your resources are also secured by spring.
You may try to move your resources in a js (, css...) folder and add this to your configuration:
<security:intercept-url pattern="/js/**" filters="none" />
(could not test this. no spring security project near me ;) )
edit:
just got a note that this is old spring security ( < 3.1 ) syntax and deprecated.
Use multiple http tags instead if you are using spring security >= 3.1 (but your code looks like old config)
<http pattern="/css/**" security="none"/>
from: http://docs.spring.io/spring-security/site/docs/3.1.x/reference/springsecurity-single.html#ns-form-and-basic

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.

Resources