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

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

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

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

spring security and mvc

I am using spring security and some mvc controllers. I am not able to make it work. Below is the error I get.
org.springframework.web.servlet.PageNotFound - No mapping found for HTTP request with URI [/auth/ping] in DispatcherServlet with name 'application'
It would be great if anyone can figure out what's wrong with my code
below are my files
web.xml
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.5"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>Out of school network backend</display-name>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/log4j.properties</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/application-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- CORS Filter -->
<filter>
<filter-name>corsFilter</filter-name>
<filter-class>com.myproj.filters.SimpleCORSFilter</filter-class>
</filter>
<!-- Spring Security Filter -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>corsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>application</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>application</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
Below is my application context:
<?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"
xmlns:sec="http://www.springframework.org/schema/security"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:mongo="http://www.springframework.org/schema/data/mongo"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/data/mongo http://www.springframework.org/schema/data/mongo/spring-mongo-1.5.xsd">
<context:annotation-config />
<context:component-scan base-package="com.myproj.controllers" />
<mvc:annotation-driven />
<!-- mongodb -->
<mongo:db-factory id="mongoDbFactory"
host="<ip address>"
port="27017"
dbname="mongotest"
username="username"
password="password"/>
<bean id="mongoTemplate" class="org.springframework.data.mongodb.core.MongoTemplate">
<constructor-arg ref="mongoDbFactory" />
</bean>
<mongo:repositories base-package="com.myproj.repositories" />
<!-- Global Security Settings -->
<sec:global-method-security pre-post-annotations="enabled" />
<sec:http use-expressions="true" disable-url-rewriting="true" auto-config="true"
entry-point-ref="authenticationEntryPoint"
authentication-manager-ref="authenticationManager">
<sec:intercept-url pattern="/auth/*" access="isAnonymous()" />
<sec:intercept-url method="POST" pattern="/be/user" access="isAnonymous()" />
<sec:intercept-url pattern="/home" access="isAnonymous()" />
<sec:intercept-url pattern="/api/*" access="hasRole('ROLE_USER')" />
<sec:form-login login-processing-url="/auth/login"
default-target-url="/account"
username-parameter="username"
password-parameter="password"
authentication-failure-url="/login?loginError"/>
<sec:logout logout-success-url="/login?logout" />
</sec:http>
<bean id="authenticationEntryPoint" class="org.springframework.security.web.authentication.Http403ForbiddenEntryPoint" />
<bean id="userDetailsService" class="com.myproj.security.UserDetailsServiceImpl" />
<sec:authentication-manager alias="authenticationManager">
<sec:authentication-provider user-service-ref="userDetailsService" />
</sec:authentication-manager>
Below is the controller:
package com.myproj.controllers;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.http.HttpStatus;
public class PingController {
#RequestMapping(value = "auth/ping", method = RequestMethod.GET)
#ResponseStatus(HttpStatus.OK)
public #ResponseBody String login() {
return "unprotected";
}
#RequestMapping(value = "api/protected", method = RequestMethod.GET)
#ResponseStatus(HttpStatus.OK)
public #ResponseBody String getpro() {
return "protected";
}
}
You forgot #Controller on your PingController class.

org.springframework.web.servlet.DispatcherServlet noHandlerFound for login.jsp

my jsps are under views,
web.xml :
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Spring-MVC-Security</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/servletDispatcher-servlet.xml,/WEB-INF/spring-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>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>servletDispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>servletDispatcher</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>login</welcome-file>
</welcome-file-list>
</web-app>
servletDispatcher-servlet.xml :
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
<mvc:annotation-driven/>
<!-- <mvc:default-servlet-handler/> -->
<context:component-scan base-package="com.spring.controller"></context:component-scan>
<context:component-scan base-package="com.spring.util"></context:component-scan>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
spring-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"
xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">
<security:http auto-config="true" use-expressions="true">
<security:intercept-url pattern="/login" access="permitAll" />
<security:intercept-url pattern="/logout" access="permitAll" />
<security:intercept-url pattern="/accessdenied" access="permitAll" />
<security:intercept-url pattern="/**" access="hasRole('ROLE_USER')" />
<security:form-login login-page="/login" default-target-url="/list" authentication-failure-url="/accessdenied" />
<security:logout logout-success-url="/logout" />
</security:http>
<security:authentication-manager alias="authenticationManager">
<security:authentication-provider>
<security:user-service>
<security:user name="lokesh" password="password" authorities="ROLE_USER" />
</security:user-service>
</security:authentication-provider>
</security:authentication-manager>
</beans>
Controller :
package com.spring.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
#Controller
public class LoginController {
#RequestMapping({"/","/login"})
public String login()
{
return "login";
}
}
When I am trying to hit
http://localhost:8080/Spring-MVC-Security/ ,
url is getting redirected to
http://localhost:8080/Spring-MVC-Security/login
but I am getting 404 error from tomcat and getting following warning at the console:
Jan 13, 2014 12:03:41 PM org.springframework.web.servlet.DispatcherServlet noHandlerFound
WARNING: No mapping found for HTTP request with URI [/Spring-MVC-Security/WEB-INF/views/login.jsp] in DispatcherServlet with name 'servletDispatcher'
It seems like servletDispatcher is hit again after view resolution.
Please advise. Thanks
First off, you're loading the servletDispatcher context twice. The dispatcher servlet will automatically discover the /WEB-INF/servletDispatcher-servlet.xml file based on conventions - so this does not need to be specified in the contextConfigLocation
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
<!-- Remove servletDispatcher-servlet.xml -->
/WEB-INF/spring-security.xml
</param-value>
</context-param>
Try changing your dispatcher servlet mapping from /* to /
<servlet-mapping>
<servlet-name>servletDispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Also - since your login controller is not doing anything other than returning the login view, you could replace it with a view controller.
<mvc:view-controller path="/login" />

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