Spring doesn't Reject Protected Url access - spring

I have implemented spring security it was working fine but suddenly it stopped working.
Now when I try to access a protected url it doesn't reject, it allows me to open url.
when I try to login with valid user it does call loginSuccessHandler but doesn't redirect to secure/applications.html page.
Sorry it is bit lengthy detail, I am really stuck :(.
Spring Logging
20:41:04,555 DEBUG [org.springframework.security.web.util.AntPathRequestMatcher] - Checking match of request : '/j_spring_security_check'; against '/resources/**'
20:41:04,556 DEBUG [org.springframework.security.web.FilterChainProxy] - /j_spring_security_check at position 1 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
20:41:04,556 DEBUG [org.springframework.security.web.context.HttpSessionSecurityContextRepository] - No HttpSession currently exists
20:41:04,556 DEBUG [org.springframework.security.web.context.HttpSessionSecurityContextRepository] - No SecurityContext was available from the HttpSession: null. A new one will be created.
20:41:04,556 DEBUG [org.springframework.security.web.FilterChainProxy] - /j_spring_security_check at position 2 of 11 in additional filter chain; firing Filter: 'LogoutFilter'
20:41:04,556 DEBUG [org.springframework.security.web.FilterChainProxy] - /j_spring_security_check at position 3 of 11 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
20:41:04,556 DEBUG [org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter] - Request is to process authentication
20:41:04,557 DEBUG [org.springframework.security.authentication.ProviderManager] - Authentication attempt using org.springframework.security.authentication.dao.DaoAuthenticationProvider
Hibernate: select this_.id as id1_12_1_, this_.date as date2_12_1_, this_.email as email3_12_1_, this_.firstName as firstNam4_12_1_, this_.lastName as lastName5_12_1_, this_.password as password6_12_1_, this_.phoneNumber as phoneNum7_12_1_, this_.role as role8_12_1_, registerst2_.id as id1_11_0_, registerst2_.active as active2_11_0_, registerst2_.sessionExpiry as sessionE3_11_0_, registerst2_.sessionString as sessionS4_11_0_ from User this_ left outer join RegisterStatus registerst2_ on this_.id=registerst2_.id where this_.email=?
20:41:07,736 WARN [org.springframework.security.authentication.event.LoggerListener] - Authentication event AuthenticationSuccessEvent: yahya.arshad#gmail.com; details: org.springframework.security.web.authentication.WebAuthenticationDetails#ffff8868: RemoteIpAddress: 0:0:0:0:0:0:0:1%0; SessionId: null
20:41:07,737 DEBUG [org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter] - Authentication success. Updating SecurityContextHolder to contain: org.springframework.security.authentication.UsernamePasswordAuthenticationToken#48f0accc: Principal: com.fyp.ptma.security.AuthorisedUser#48f0db60: Username: yahya.arshad#gmail.com; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Not granted any authorities; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#ffff8868: RemoteIpAddress: 0:0:0:0:0:0:0:1%0; SessionId: null; Not granted any authorities
20:41:07,737 DEBUG [org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices] - Did not send remember-me cookie (principal did not set parameter '_spring_security_remember_me')
20:41:07,737 DEBUG [org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices] - Remember-me login not requested.
20:41:07,737 WARN [org.springframework.security.authentication.event.LoggerListener] - Authentication event InteractiveAuthenticationSuccessEvent: yahya.arshad#gmail.com; details: org.springframework.security.web.authentication.WebAuthenticationDetails#ffff8868: RemoteIpAddress: 0:0:0:0:0:0:0:1%0; SessionId: null
20:41:09,038 DEBUG [org.springframework.security.web.session.HttpSessionEventPublisher] - Publishing event: org.springframework.security.web.session.HttpSessionCreatedEvent[source=org.mortbay.jetty.servlet.HashSessionManager$Session:ap7q19yq3oul#1156618876]
20:41:09,039 DEBUG [org.springframework.security.web.context.HttpSessionSecurityContextRepository] - SecurityContext stored to HttpSession: 'org.springframework.security.core.context.SecurityContextImpl#48f0accc: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken#48f0accc: Principal: com.fyp.ptma.security.AuthorisedUser#48f0db60: Username: yahya.arshad#gmail.com; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Not granted any authorities; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#ffff8868: RemoteIpAddress: 0:0:0:0:0:0:0:1%0; SessionId: null; Not granted any authorities'
20:41:09,041 DEBUG [org.springframework.security.web.context.SecurityContextPersistenceFilter] - SecurityContextHolder now cleared, as request processing completed
20:41:09,047 DEBUG [org.springframework.security.web.util.AntPathRequestMatcher] - Checking match of request : '/secure/applications.html'; against '/resources/**'
20:41:09,047 DEBUG [org.springframework.security.web.FilterChainProxy] - /secure/applications.html at position 1 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
20:41:09,047 DEBUG [org.springframework.security.web.context.HttpSessionSecurityContextRepository] - Obtained a valid SecurityContext from SPRING_SECURITY_CONTEXT: 'org.springframework.security.core.context.SecurityContextImpl#48f0accc: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken#48f0accc: Principal: com.fyp.ptma.security.AuthorisedUser#48f0db60: Username: yahya.arshad#gmail.com; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Not granted any authorities; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#ffff8868: RemoteIpAddress: 0:0:0:0:0:0:0:1%0; SessionId: null; Not granted any authorities'
20:41:09,047 DEBUG [org.springframework.security.web.FilterChainProxy] - /secure/applications.html at position 2 of 11 in additional filter chain; firing Filter: 'LogoutFilter'
20:41:09,048 DEBUG [org.springframework.security.web.FilterChainProxy] - /secure/applications.html at position 3 of 11 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
20:41:09,048 DEBUG [org.springframework.security.web.FilterChainProxy] - /secure/applications.html at position 4 of 11 in additional filter chain; firing Filter: 'BasicAuthenticationFilter'
20:41:09,048 DEBUG [org.springframework.security.web.FilterChainProxy] - /secure/applications.html at position 5 of 11 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
20:41:09,048 DEBUG [org.springframework.security.web.FilterChainProxy] - /secure/applications.html at position 6 of 11 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
20:41:09,048 DEBUG [org.springframework.security.web.FilterChainProxy] - /secure/applications.html at position 7 of 11 in additional filter chain; firing Filter: 'RememberMeAuthenticationFilter'
20:41:09,048 DEBUG [org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter] - SecurityContextHolder not populated with remember-me token, as it already contained: 'org.springframework.security.authentication.UsernamePasswordAuthenticationToken#48f0accc: Principal: com.fyp.ptma.security.AuthorisedUser#48f0db60: Username: yahya.arshad#gmail.com; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Not granted any authorities; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#ffff8868: RemoteIpAddress: 0:0:0:0:0:0:0:1%0; SessionId: null; Not granted any authorities'
20:41:09,048 DEBUG [org.springframework.security.web.FilterChainProxy] - /secure/applications.html at position 8 of 11 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
20:41:09,048 DEBUG [org.springframework.security.web.authentication.AnonymousAuthenticationFilter] - SecurityContextHolder not populated with anonymous token, as it already contained: 'org.springframework.security.authentication.UsernamePasswordAuthenticationToken#48f0accc: Principal: com.fyp.ptma.security.AuthorisedUser#48f0db60: Username: yahya.arshad#gmail.com; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Not granted any authorities; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#ffff8868: RemoteIpAddress: 0:0:0:0:0:0:0:1%0; SessionId: null; Not granted any authorities'
20:41:09,048 DEBUG [org.springframework.security.web.FilterChainProxy] - /secure/applications.html at position 9 of 11 in additional filter chain; firing Filter: 'SessionManagementFilter'
20:41:09,048 DEBUG [org.springframework.security.web.FilterChainProxy] - /secure/applications.html at position 10 of 11 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
20:41:09,048 DEBUG [org.springframework.security.web.FilterChainProxy] - /secure/applications.html at position 11 of 11 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
20:41:09,049 DEBUG [org.springframework.security.web.access.intercept.FilterSecurityInterceptor] - Secure object: FilterInvocation: URL: /secure/applications.html; Attributes: [permitAll]
20:41:09,049 DEBUG [org.springframework.security.web.access.intercept.FilterSecurityInterceptor] - Previously Authenticated: org.springframework.security.authentication.UsernamePasswordAuthenticationToken#48f0accc: Principal: com.fyp.ptma.security.AuthorisedUser#48f0db60: Username: yahya.arshad#gmail.com; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Not granted any authorities; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#ffff8868: RemoteIpAddress: 0:0:0:0:0:0:0:1%0; SessionId: null; Not granted any authorities
20:41:09,049 DEBUG [org.springframework.security.access.vote.AffirmativeBased] - Voter: org.springframework.security.web.access.expression.WebExpressionVoter#3aa8c31b, returned: 1
20:41:09,049 DEBUG [org.springframework.security.web.access.intercept.FilterSecurityInterceptor] - Authorization successful
20:41:09,049 DEBUG [org.springframework.security.web.access.intercept.FilterSecurityInterceptor] - RunAsManager did not change Authentication object
20:41:09,049 DEBUG [org.springframework.security.web.FilterChainProxy] - /secure/applications.html reached end of additional filter chain; proceeding with original chain
20:41:09,053 DEBUG [org.springframework.security.web.access.ExceptionTranslationFilter] - Chain processed normally
20:41:09,053 DEBUG [org.springframework.security.web.context.SecurityContextPersistenceFilter] - SecurityContextHolder now cleared, as request processing completed
LoginSuccessHandler.java
public class LoginSuccessHandler implements AuthenticationSuccessHandler,
AuthenticationFailureHandler {
public void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response, Authentication auth)
throws IOException, ServletException {
request.getSession(true).setAttribute("user", auth.getPrincipal());
request.setAttribute("user", auth.getPrincipal());
**response.sendRedirect("secure/applications.html");** // it does't redirect
}
public void onAuthenticationFailure(HttpServletRequest request,
HttpServletResponse response, AuthenticationException auth)
throws IOException, ServletException {
// TODO Auto-generated method stub
request.getSession(true).setAttribute("error", auth.getMessage());
request.setAttribute("error", auth.getMessage());
response.sendRedirect("login.html?error=true");
}
}
security-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<context:component-scan base-package="com.fyp.ptma" />
<beans:bean id="loggerListener"
class="org.springframework.security.authentication.event.LoggerListener" />
<global-method-security pre-post-annotations="enabled" />
<http pattern="/resources/**" security="none" />
<http use-expressions="true" auto-config="true">
<intercept-url pattern="/**" access="permitAll" />
<intercept-url pattern="/secure/*" access="isAuthenticated()" />
<intercept-url pattern="/j_spring_security_check"
access="permitAll" />
<intercept-url pattern="/processRegistration.html"
access="permitAll" />
<form-login login-page="/login.html" default-target-url="/secure/fileUpload.html"
authentication-failure-url="/login.html?error=true"
login-processing-url="/j_spring_security_check"
authentication-success-handler-ref="loginSuccessHandler"
/>
<logout />
<remember-me user-service-ref="userDetailsService" />
<access-denied-handler error-page="/login.html?error=true" />
</http>
<authentication-manager>
<authentication-provider user-service-ref="userDetailsService">
<password-encoder hash="plaintext" />
</authentication-provider>
</authentication-manager>
<beans:bean id="userDetailsService"
class="com.fyp.ptma.dao.service.UserDetailsServiceImpl">
</beans:bean>
<beans:bean id="loginSuccessHandler" class="com.fyp.ptma.security.LoginSuccessHandler" />
servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing
infrastructure -->
<beans:bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving
up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by #Controllers to .jsp resources
in the /WEB-INF/views directory -->
<beans:bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="com.fyp.ptma.controllers" />
</beans:beans>
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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/log4j.properties</param-value>
</context-param>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/root-context.xml
/WEB-INF/spring/appServlet/security-context.xml
/WEB-INF/hibernate/hibernate-config.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>
<!-- Processes application requests -->
<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>
<session-config>
<session-timeout>120</session-timeout>
</session-config>
</web-app>

You should move
<intercept-url pattern="/**" access="permitAll" />
after
<intercept-url pattern="/secure/*" access="isAuthenticated()" />
in your security-context.xml

Related

Spring security: Can not access target page after entering proper credentials

I am trying to create a basic Spring Security (3.0) application following the common tutorials from internet. However, even after entering configured credentials, login page is opening again. The debug logs show that the user is being authenticated as anonymous user. Please let me know what I am missing.
Here's my web.xml:-
<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"
id="WebApp_ID" version="3.0">
<display-name>Spring Security Example</display-name>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-security.xml</param-value>
</context-param>
<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>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<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>
My spring-security.xml:-
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans
xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security.xsd">
<http >
<intercept-url pattern="/app/*"
access="ROLE_USER" />
<form-login login-page="/app/login/"
default-target-url="/app/home/"
authentication-failure-url="/app/login?error=true" />
</http>
<authentication-manager>
<authentication-provider>
<user-service>
<user name="sumit" password="1234"
authorities="ROLE_USER" />
</user-service>
</authentication-provider>
</authentication-manager>
</beans:beans>
My login.jsp:-
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Login</title>
</head>
<body>
<h2>Login page</h2>
<form:form method="POST" action="../home" commandName="user">
Username: <form:input path="username" />
<br>
Password: <form:input path="password" />
<br>
<input type="submit" value="Login">
</form:form>
</body>
</html>
My Controller:-
package com.test.basicspring.controller;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.test.model.UserModel;
#Controller
#RequestMapping(value = "/app")
public class HelloWorldController {
private Logger logger = Logger.getLogger(HelloWorldController.class);
#RequestMapping(method = RequestMethod.GET, value = "/hello")
public void SayHello(HttpServletResponse response) {
System.out.println("Hello World");
logger.info("Logging Hello World");
try {
response.getWriter().write("Request completed");
} catch (IOException e) {
e.printStackTrace();
}
}
#RequestMapping(method = RequestMethod.GET, value = "/login")
public String login(Model modelMap) {
System.out.println("In login method");
modelMap.addAttribute("user", new UserModel());
return "login";
}
#RequestMapping(method = RequestMethod.POST, value = "/home")
public String home() {
System.out.println("Login successful");
return "";
}
}
Debug logs after submitting login credentials:-
DEBUG 2020-01-18 10:51:36,856 [http-nio-8080-exec-6] org.springframework.security.web.FilterChainProxy - Converted URL to lowercase, from: '/app/home'; to: '/app/home'
DEBUG 2020-01-18 10:51:36,856 [http-nio-8080-exec-6] org.springframework.security.web.FilterChainProxy - Candidate is: '/app/home'; pattern is /**; matched=true
DEBUG 2020-01-18 10:51:36,856 [http-nio-8080-exec-6] org.springframework.security.web.FilterChainProxy - /app/home at position 1 of 8 in additional filter chain; firing Filter: 'org.springframework.security.web.context.SecurityContextPersistenceFilter#26f6ad34'
DEBUG 2020-01-18 10:51:36,856 [http-nio-8080-exec-6] org.springframework.security.web.context.HttpSessionSecurityContextRepository - HttpSession returned null object for SPRING_SECURITY_CONTEXT
DEBUG 2020-01-18 10:51:36,856 [http-nio-8080-exec-6] org.springframework.security.web.context.HttpSessionSecurityContextRepository - No SecurityContext was available from the HttpSession: org.apache.catalina.session.StandardSessionFacade#4f884b44. A new one will be created.
DEBUG 2020-01-18 10:51:36,856 [http-nio-8080-exec-6] org.springframework.security.web.FilterChainProxy - /app/home at position 2 of 8 in additional filter chain; firing Filter: 'org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#7d0a1070'
DEBUG 2020-01-18 10:51:36,856 [http-nio-8080-exec-6] org.springframework.security.web.FilterChainProxy - /app/home at position 3 of 8 in additional filter chain; firing Filter: 'org.springframework.security.web.savedrequest.RequestCacheAwareFilter#542dcf66'
DEBUG 2020-01-18 10:51:36,856 [http-nio-8080-exec-6] org.springframework.security.web.savedrequest.DefaultSavedRequest - pathInfo: both null (property equals)
DEBUG 2020-01-18 10:51:36,857 [http-nio-8080-exec-6] org.springframework.security.web.savedrequest.DefaultSavedRequest - queryString: both null (property equals)
DEBUG 2020-01-18 10:51:36,857 [http-nio-8080-exec-6] org.springframework.security.web.savedrequest.DefaultSavedRequest - requestURI: arg1=/springSecurityExample/app/hello; arg2=/springSecurityExample/app/home (property not equals)
DEBUG 2020-01-18 10:51:36,857 [http-nio-8080-exec-6] org.springframework.security.web.savedrequest.HttpSessionRequestCache - saved request doesn't match
DEBUG 2020-01-18 10:51:36,857 [http-nio-8080-exec-6] org.springframework.security.web.FilterChainProxy - /app/home at position 4 of 8 in additional filter chain; firing Filter: 'org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#6d55a0ba'
DEBUG 2020-01-18 10:51:36,857 [http-nio-8080-exec-6] org.springframework.security.web.FilterChainProxy - /app/home at position 5 of 8 in additional filter chain; firing Filter: 'org.springframework.security.web.authentication.AnonymousAuthenticationFilter#6ec0b31f'
DEBUG 2020-01-18 10:51:36,857 [http-nio-8080-exec-6] org.springframework.security.web.authentication.AnonymousAuthenticationFilter - Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken#6fabe8e0: Principal: anonymousUser; Password: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#fffe9938: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: F09C61DDA9D42B649B89CD650863A289; Granted Authorities: ROLE_ANONYMOUS'
DEBUG 2020-01-18 10:51:36,857 [http-nio-8080-exec-6] org.springframework.security.web.FilterChainProxy - /app/home at position 6 of 8 in additional filter chain; firing Filter: 'org.springframework.security.web.session.SessionManagementFilter#1f29202'
DEBUG 2020-01-18 10:51:36,857 [http-nio-8080-exec-6] org.springframework.security.web.FilterChainProxy - /app/home at position 7 of 8 in additional filter chain; firing Filter: 'org.springframework.security.web.access.ExceptionTranslationFilter#77240701'
DEBUG 2020-01-18 10:51:36,857 [http-nio-8080-exec-6] org.springframework.security.web.FilterChainProxy - /app/home at position 8 of 8 in additional filter chain; firing Filter: 'org.springframework.security.web.access.intercept.FilterSecurityInterceptor#72e500b4'
DEBUG 2020-01-18 10:51:36,857 [http-nio-8080-exec-6] org.springframework.security.web.access.intercept.DefaultFilterInvocationSecurityMetadataSource - Converted URL to lowercase, from: '/app/home'; to: '/app/home'
DEBUG 2020-01-18 10:51:36,857 [http-nio-8080-exec-6] org.springframework.security.web.access.intercept.DefaultFilterInvocationSecurityMetadataSource - Candidate is: '/app/home'; pattern is /app/*; matched=true
DEBUG 2020-01-18 10:51:36,857 [http-nio-8080-exec-6] org.springframework.security.web.access.intercept.FilterSecurityInterceptor - Secure object: FilterInvocation: URL: /app/home; Attributes: [ROLE_USER]
DEBUG 2020-01-18 10:51:36,857 [http-nio-8080-exec-6] org.springframework.security.web.access.intercept.FilterSecurityInterceptor - Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken#6fabe8e0: Principal: anonymousUser; Password: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#fffe9938: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: F09C61DDA9D42B649B89CD650863A289; Granted Authorities: ROLE_ANONYMOUS
DEBUG 2020-01-18 10:51:36,857 [http-nio-8080-exec-6] org.springframework.security.access.vote.AffirmativeBased - Voter: org.springframework.security.access.vote.RoleVoter#4bb7d66d, returned: -1
DEBUG 2020-01-18 10:51:36,857 [http-nio-8080-exec-6] org.springframework.security.access.vote.AffirmativeBased - Voter: org.springframework.security.access.vote.AuthenticatedVoter#eb5417f, returned: 0
TRACE 2020-01-18 10:51:36,857 [http-nio-8080-exec-6] org.springframework.web.context.support.XmlWebApplicationContext - Publishing event in Root WebApplicationContext: org.springframework.security.access.event.AuthorizationFailureEvent[source=FilterInvocation: URL: /app/home]
DEBUG 2020-01-18 10:51:36,857 [http-nio-8080-exec-6] org.springframework.security.web.access.ExceptionTranslationFilter - Access is denied (user is anonymous); redirecting to authentication entry point
org.springframework.security.access.AccessDeniedException: Access is denied
I was able to make above code work by specifying action attribute and login-processing-url both to '/login'. With this configuration, spring activates inbuilt filter for username and password validation. Then, it goes to endpoint specified by default-target-url.

HttpSession is now null, but was not null at start of request; session was invalidated, so do not create a new session

After user password is being reset user is supposed to redirected to security questions page(/PP/enduser/securityQuestions.do?clear=true') instead user is getting AccessDeniedException because session is invalidated and user is given anonymousUser authentication. I tried the solution from other similar problem An Authentication object was not found in the SecurityContext - Spring 3.2.2 but the solution not working for me.
AM using jdk 7, spring-security-web-3.1.4.RELEASE, spring-security-core-3.1.4.RELEASE and Tomcat 7
Below is my Authentication success handler
#Component
#Primary
public class CPAuthenticationSuccessHandler extends DCAuthenticationSuccessHandler {
#Autowired
private CollaborationSecurityService collabSecurityService;
#Autowired
private AuthenticationFilterConfiguration authenticationConfiguration;
#Autowired
private FailedLoginsLock failedLoginsLock;
private static final String SECURITY_QUESTIONS_URL = "/enduser/securityQuestions.do?clear=true";
private static final Logger LOGGER = Logger.getInstance("dc.auth");
#Override
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof AuthenticationSuccessEvent)
try {
AuthenticationSuccessEvent authenticationSuccessEvent = (AuthenticationSuccessEvent) event;
SecurityContext ctx = SecurityContextHolder.createEmptyContext();
SecurityContextHolder.setContext(ctx);
ctx.setAuthentication(authenticationSuccessEvent.getAuthentication());
} finally {
SecurityContextHolder.clearContext();
}
super.onApplicationEvent(event);
}
#Override
public void onAuthenticationSuccess(final HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
new DefaultRedirectStrategy().sendRedirect(request, response,
this.onCPAuthenticationSuccessUrl(request, response, authentication));
}
public String onCPAuthenticationSuccessUrl(final HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
LOGGER.log(Level.INFO, "Successful Authentication Principal--> " + authentication.getPrincipal());
boolean isNewSession = false;
Session session = null;
try {
if (!sessionHandler.sessionAlreadyBound(sessionFactory)) {
session = sessionHandler.initiateSession(sessionFactory);
sessionHandler.beginTransaction(session);
isNewSession = true;
}
if (!SecurityHelper.isCurrentUserAnonymous()
&& collabSecurityService.needSecurityQuestionSetup(authentication.getName()))
return SECURITY_QUESTIONS_URL;
else
return super.onAuthenticationSuccessUrl(request, response, authentication);
} finally {
if (isNewSession) {
sessionHandler.endTransaction(false, sessionFactory);
}
}
}
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
super.setApplicationContext(applicationContext);
}
}
security-applicationContext.xml
<!-- TRUSTED LOGIN CONFIGURATION -->
<http use-expressions="true" auto-config="false" disable-url-rewriting="true" entry-point-ref="http403ForbiddenEntryPoint"
request-matcher-ref="trustedRequestMatcher">
<request-cache ref="httpSessionRequestCache"/>
<intercept-url pattern="/enduser/**" access="isAuthenticated()" />
<intercept-url pattern="/index.do" access="isAnonymous()" />
<custom-filter position="PRE_AUTH_FILTER" ref="trustedAuthenticationFilter" />
<http-basic />
<anonymous />
<session-management session-authentication-strategy-ref="customSessionFixationProtectionStrategy" />
</http>
<beans:bean id="trustedAuthenticationFilter" class="o.s.s.web.authentication.preauth.RequestHeaderAuthenticationFilter">
<beans:property name="principalRequestHeader" value="X-Remote-Authenticate"/>
<beans:property name="authenticationManager" ref="authenticationManager" />
<beans:property name="exceptionIfHeaderMissing" value="false" />
</beans:bean>
<beans:bean id="httpSessionRequestCache" class="o.s.s.web.savedrequest.HttpSessionRequestCache">
<beans:property name="createSessionAllowed" value="false" />
</beans:bean>
<!-- LOCAL LOGIN CONFIGURATION -->
<http use-expressions="true" auto-config="false" disable-url-rewriting="true" entry-point-ref="loginUrlAuthenticationEntryPoint"
request-matcher-ref="localAuthRequestMatcher">
<request-cache ref="httpSessionRequestCache"/>
<intercept-url pattern="/admin/**" access="hasRole('ADMIN_PERMISSION')" />
<intercept-url pattern="/system/**" access="hasRole('ADMIN_PERMISSION')" />
<intercept-url pattern="/enduser/**" access="isAuthenticated()" />
<intercept-url pattern="/changePassword.do" access="permitAll"/>
<intercept-url pattern="/index.do" access="isAnonymous()" />
<custom-filter after="SECURITY_CONTEXT_FILTER" ref="welcomePageRedirectFilter" />
<custom-filter before="LOGOUT_FILTER" ref="internalAuthenticationFilter" />
<form-login login-page="/index.do" authentication-failure-handler-ref="DCAuthenticationFailureHandler" authentication-success-handler-ref="DCAuthenticationSuccessHandler" />
<http-basic />
<anonymous />
<session-management session-authentication-strategy-ref="customSessionFixationProtectionStrategy" />
<logout success-handler-ref="localLogoutSuccessHandler" />
</http>
<beans:bean id="exceptionTranslator"
class="o.s.s.web.access.ExceptionTranslationFilter">
<beans:constructor-arg><beans:ref bean="loginUrlAuthenticationEntryPoint" /></beans:constructor-arg>
</beans:bean>
<beans:bean id="localLogoutSuccessHandler"
class="com.dc.core.security.authentication.impl.CustomLogoutSuccessHandler">
<beans:property name="defaultTargetUrl" value="/index.do" />
</beans:bean>
<!-- SITEMINDER AND SAML LOGIN CONFIGURATION -->
<http use-expressions="true" auto-config="false" disable-url-rewriting="true" entry-point-ref="http403ForbiddenEntryPoint"
request-matcher-ref="siteminderSamlAuthRequestMatcher">
<request-cache ref="httpSessionRequestCache"/>
<intercept-url pattern="/admin/**" access="hasRole('ADMIN_PERMISSION')" />
<intercept-url pattern="/system/**" access="hasRole('ADMIN_PERMISSION')" />
<intercept-url pattern="/enduser/**" access="isAuthenticated()" />
<intercept-url pattern="/changePassword.do" access="isAuthenticated()"/>
<intercept-url pattern="/index.do" access="isAnonymous()" />
<custom-filter after="SECURITY_CONTEXT_FILTER" ref="welcomePageRedirectFilter" />
<custom-filter before="LOGOUT_FILTER" ref="internalAuthenticationFilter" />
<custom-filter position="PRE_AUTH_FILTER" ref="siteminderSamlFilter" />
<http-basic />
<anonymous />
<session-management session-authentication-strategy-ref="customSessionFixationProtectionStrategy" />
<logout logout-success-url="/index.do" />
</http>
<beans:bean id="siteminderSamlFilter" class="com.dc.core.security.authentication.impl.RequestHeaderAuthenticationFilter">
<beans:property name="principalRequestHeader" value="SM_USER"/>
<beans:property name="authenticationManager" ref="authenticationManager" />
<beans:property name="exceptionIfHeaderMissing" value="false" />
<!-- As the default value of roleVoter is "ROLE_", overriding the value to empty string -->
<beans:bean id="roleVoter" class="o.s.s.access.vote.RoleVoter">
<beans:property name="rolePrefix" value="" />
</beans:bean>
<beans:bean id="loginUrlAuthenticationEntryPoint"
class="o.s.s.web.authentication.LoginUrlAuthenticationEntryPoint">
<beans:constructor-arg type="java.lang.String" value="/index.do"></beans:constructor-arg>
</beans:bean>
<beans:bean id="http403ForbiddenEntryPoint"
class="o.s.s.web.authentication.Http403ForbiddenEntryPoint">
</beans:bean>
<beans:bean id="saltSource" class="o.s.s.authentication.dao.SystemWideSaltSource">
<beans:property name="systemWideSalt" value="dcRules!"/>
</beans:bean>
<beans:bean id="passwordEncoder" class="o.s.s.authentication.encoding.ShaPasswordEncoder"/>
<beans:bean id="daoAuthenticationProvider"
class="o.s.s.authentication.dao.DaoAuthenticationProvider">
<beans:property name="saltSource" ref="saltSource"/>
<beans:property name="passwordEncoder" ref="passwordEncoder"/>
<beans:property name="userDetailsService" ref="userDetailsService"/>
<beans:property name="preAuthenticationChecks" ref="DCPreAuthenticationChecks" />
<beans:property name="postAuthenticationChecks" ref="DCPostAuthenticationChecks" />
</beans:bean>
<beans:bean id="userInfo" class="com.dc.core.security.model.impl.User" scope="session">
<aop:scoped-proxy/>
</beans:bean>
<beans:bean id="userDetailsService" class="com.dc.core.security.authentication.impl.DCUserDetailsService">
</beans:bean>
<beans:bean id="securityLoggerListener" class="o.s.s.access.event.LoggerListener"></beans:bean>
<!-- JMX Mbeans:beans configuration -->
<beans:bean id="registry" class="org.springframework.remoting.rmi.RmiRegistryFactoryBean">
<beans:property name="port" value="${security.jmx.remote.port}" />
</beans:bean>
<beans:bean id="exporter" class="org.springframework.jmx.export.MBeanExporter">
<beans:property name="assembler" ref="assembler" />
<beans:property name="namingStrategy" ref="namingStrategy" />
<beans:property name="autodetect" value="true" />
</beans:bean>
<beans:bean id="jmxAttributeSource"
class="org.springframework.jmx.export.annotation.AnnotationJmxAttributeSource" />
<beans:bean id="assembler"
class="org.springframework.jmx.export.assembler.MetadataMBeanInfoAssembler">
<beans:property name="attributeSource" ref="jmxAttributeSource" />
</beans:bean>
<beans:bean id="namingStrategy"
class="org.springframework.jmx.export.naming.MetadataNamingStrategy">
<beans:property name="attributeSource" ref="jmxAttributeSource" />
</beans:bean>
<beans:bean id="serverConnector"
class="org.springframework.jmx.support.ConnectorServerFactoryBean">
<beans:property name="objectName" value="connector:name=rmi" />
<beans:property name="serviceUrl"
value="${security.jmx.remote.url}" />
</beans:bean>
<beans:bean id="clientConnector"
class="org.springframework.jmx.support.MBeanServerConnectionFactoryBean">
<beans:property name="serviceUrl"
value="${security.jmx.remote.url}" />
</beans:bean>
my web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<context-param>
<param-name>contextClass</param-name>
<param-value>
com.dc.core.spring.CustomXmlWebApplicationContext
</param-value>
</context-param>
<context-param>
<param-name>
javax.servlet.jsp.jstl.fmt.localizationContext
</param-name>
<param-value>messages</param-value>
</context-param>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/classes/log4j.properties</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener
</listener-class>
</listener>
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
<listener>
<listener-class>
com.dc.core.security.listener.SessionListener
</listener-class>
</listener>
After the user is redirected to /enduser/securityQuestions.do page user is getting customaccessdenied exception and kicked back to login page(index.do)
2014-09-09 22:41:09,204 DEBUG | o.s.s.web.context.SecurityContextPersistenceFilter | | 91U89hqS96LB | SecurityContextHolder now cleared, as request processing completed
2014-09-09 22:41:14,727 DEBUG | o.s.s.w.FilterChainProxy | | kfHMkpzvUJYw | /j_spring_security_check at position 1 of 12 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2014-09-09 22:41:14,728 DEBUG | o.s.s.w.context.HttpSessionSecurityContextRepository | | kfHMkpzvUJYw | HttpSession returned null object for SPRING_SECURITY_CONTEXT
2014-09-09 22:41:14,729 DEBUG | o.s.s.w.context.HttpSessionSecurityContextRepository | | kfHMkpzvUJYw | No SecurityContext was available from the HttpSession: org.apache.catalina.session.StandardSessionFacade#61763e58. A new one will be created.
2014-09-09 22:41:14,730 DEBUG | o.s.s.w.FilterChainProxy | | kfHMkpzvUJYw | /j_spring_security_check at position 2 of 12 in additional filter chain; firing Filter: 'WelcomePageRedirectFilter'
2014-09-09 22:41:14,731 DEBUG | o.s.s.w.FilterChainProxy | | kfHMkpzvUJYw | /j_spring_security_check at position 3 of 12 in additional filter chain; firing Filter: 'InternalAuthenticationFilter'
2014-09-09 22:41:14,732 DEBUG | o.s.s.w.FilterChainProxy | | kfHMkpzvUJYw | /j_spring_security_check at position 4 of 12 in additional filter chain; firing Filter: 'LogoutFilter'
2014-09-09 22:41:14,733 DEBUG | o.s.s.w.FilterChainProxy | | kfHMkpzvUJYw | /j_spring_security_check at position 5 of 12 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
2014-09-09 22:41:14,734 DEBUG | o.s.s.w.authentication.UsernamePasswordAuthenticationFilter | | kfHMkpzvUJYw | Request is to process authentication
2014-09-09 22:41:14,734 DEBUG | o.s.s.authentication.ProviderManager | | kfHMkpzvUJYw | Authentication attempt using com.dc.apps.collaborationportal.security.service.CPDaoAuthenticationProvider
2014-09-09 22:41:14,745 DEBUG | o.s.s.w.FilterChainProxy | | 91U89hqS96LB | /j_spring_security_check at position 1 of 12 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2014-09-09 22:41:14,747 DEBUG | o.s.s.w.context.HttpSessionSecurityContextRepository | | 91U89hqS96LB | HttpSession returned null object for SPRING_SECURITY_CONTEXT
2014-09-09 22:41:14,747 DEBUG | o.s.s.w.context.HttpSessionSecurityContextRepository | | 91U89hqS96LB | No SecurityContext was available from the HttpSession: org.apache.catalina.session.StandardSessionFacade#61763e58. A new one will be created.
2014-09-09 22:41:14,748 DEBUG | o.s.s.w.FilterChainProxy | | 91U89hqS96LB | /j_spring_security_check at position 2 of 12 in additional filter chain; firing Filter: 'WelcomePageRedirectFilter'
2014-09-09 22:41:14,748 DEBUG | o.s.s.w.FilterChainProxy | | 91U89hqS96LB | /j_spring_security_check at position 3 of 12 in additional filter chain; firing Filter: 'InternalAuthenticationFilter'
2014-09-09 22:41:14,749 DEBUG | o.s.s.w.FilterChainProxy | | 91U89hqS96LB | /j_spring_security_check at position 4 of 12 in additional filter chain; firing Filter: 'LogoutFilter'
2014-09-09 22:41:14,750 DEBUG | o.s.s.w.FilterChainProxy | | 91U89hqS96LB | /j_spring_security_check at position 5 of 12 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
2014-09-09 22:41:14,750 DEBUG | o.s.s.w.authentication.UsernamePasswordAuthenticationFilter | | 91U89hqS96LB | Request is to process authentication
2014-09-09 22:41:14,751 DEBUG | o.s.s.authentication.ProviderManager | | 91U89hqS96LB | Authentication attempt using com.dc.apps.collaborationportal.security.service.CPDaoAuthenticationProvider
2014-09-09 22:41:14,792 DEBUG | o.s.s.w.authentication.UsernamePasswordAuthenticationFilter | | 91U89hqS96LB | Authentication success. Updating SecurityContextHolder to contain: o.s.s.authentication.UsernamePasswordAuthenticationToken#86969601: Principal: o.s.s.core.userdetails.User#49520377: Username: test1#dc.com; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Not granted any authorities; Credentials: [PROTECTED]; Authenticated: true; Details: o.s.s.w.authentication.WebAuthenticationDetails#fffe9938: SessionId: 0F7B56BA141C0A001C95180FE06BE864; Not granted any authorities
2014-09-09 22:41:14,798 DEBUG | o.s.s.w.authentication.UsernamePasswordAuthenticationFilter | | kfHMkpzvUJYw | Authentication success. Updating SecurityContextHolder to contain: o.s.s.authentication.UsernamePasswordAuthenticationToken#86969601: Principal: o.s.s.core.userdetails.User#49520377: Username: test1#dc.com; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Not granted any authorities; Credentials: [PROTECTED]; Authenticated: true; Details: o.s.s.w.authentication.WebAuthenticationDetails#fffe9938: SessionId: 0F7B56BA141C0A001C95180FE06BE864; Not granted any authorities
2014-09-09 22:41:14,870 DEBUG | o.s.s.w.DefaultRedirectStrategy | test1#dc.com | 91U89hqS96LB | Redirecting to '/PP/enduser/securityQuestions.do?clear=true'
2014-09-09 22:41:14,870 DEBUG | o.s.s.w.context.HttpSessionSecurityContextRepository | test1#dc.com | 91U89hqS96LB | HttpSession is now null, but was not null at start of request; session was invalidated, so do not create a new session
2014-09-09 22:41:14,870 DEBUG | o.s.s.w.context.SecurityContextPersistenceFilter | | 91U89hqS96LB | SecurityContextHolder now cleared, as request processing completed
2014-09-09 22:41:14,898 DEBUG | o.s.s.w.DefaultRedirectStrategy | test1#dc.com | kfHMkpzvUJYw | Redirecting to '/PP/enduser/securityQuestions.do?clear=true'
2014-09-09 22:41:14,899 DEBUG | o.s.s.w.context.HttpSessionSecurityContextRepository | test1#dc.com | kfHMkpzvUJYw | SecurityContext stored to HttpSession: 'o.s.s.core.context.SecurityContextImpl#86969601: Authentication: o.s.s.authentication.UsernamePasswordAuthenticationToken#86969601: Principal: o.s.s.core.userdetails.User#49520377: Username: test1#dc.com; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Not granted any authorities; Credentials: [PROTECTED]; Authenticated: true; Details: o.s.s.w.authentication.WebAuthenticationDetails#fffe9938: SessionId: 0F7B56BA141C0A001C95180FE06BE864; Not granted any authorities'
2014-09-09 22:41:14,899 DEBUG | o.s.s.w.context.SecurityContextPersistenceFilter | | kfHMkpzvUJYw | SecurityContextHolder now cleared, as request processing completed
2014-09-09 22:41:15,880 DEBUG | o.s.s.w.FilterChainProxy | | 91U89hqS96LB | /enduser/securityQuestions.do?clear=true at position 1 of 12 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2014-09-09 22:41:15,881 DEBUG | o.s.s.w.context.HttpSessionSecurityContextRepository | | 91U89hqS96LB | No HttpSession currently exists
2014-09-09 22:41:15,881 DEBUG | o.s.s.w.context.HttpSessionSecurityContextRepository | | 91U89hqS96LB | No SecurityContext was available from the HttpSession: null. A new one will be created.
2014-09-09 22:41:15,882 DEBUG | o.s.s.w.FilterChainProxy | | 91U89hqS96LB | /enduser/securityQuestions.do?clear=true at position 2 of 12 in additional filter chain; firing Filter: 'WelcomePageRedirectFilter'
2014-09-09 22:41:15,884 DEBUG | o.s.s.w.FilterChainProxy | | 91U89hqS96LB | /enduser/securityQuestions.do?clear=true at position 3 of 12 in additional filter chain; firing Filter: 'InternalAuthenticationFilter'
2014-09-09 22:41:15,884 DEBUG | o.s.s.w.FilterChainProxy | | 91U89hqS96LB | /enduser/securityQuestions.do?clear=true at position 4 of 12 in additional filter chain; firing Filter: 'LogoutFilter'
2014-09-09 22:41:15,885 DEBUG | o.s.s.w.FilterChainProxy | | 91U89hqS96LB | /enduser/securityQuestions.do?clear=true at position 5 of 12 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
2014-09-09 22:41:15,885 DEBUG | o.s.s.w.FilterChainProxy | | 91U89hqS96LB | /enduser/securityQuestions.do?clear=true at position 6 of 12 in additional filter chain; firing Filter: 'BasicAuthenticationFilter'
2014-09-09 22:41:15,886 DEBUG | o.s.s.w.FilterChainProxy | | 91U89hqS96LB | /enduser/securityQuestions.do?clear=true at position 7 of 12 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
2014-09-09 22:41:15,886 DEBUG | o.s.s.w.FilterChainProxy | | 91U89hqS96LB | /enduser/securityQuestions.do?clear=true at position 8 of 12 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
2014-09-09 22:41:15,887 DEBUG | o.s.s.w.FilterChainProxy | | 91U89hqS96LB | /enduser/securityQuestions.do?clear=true at position 9 of 12 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
2014-09-09 22:41:15,888 DEBUG | o.s.s.w.authentication.AnonymousAuthenticationFilter | anonymousUser | 91U89hqS96LB | Populated SecurityContextHolder with anonymous token: 'o.s.s.authentication.AnonymousAuthenticationToken#6faab5ec: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: o.s.s.w.authentication.WebAuthenticationDetails#ffffc434: SessionId: null; Granted Authorities: ROLE_ANONYMOUS'
2014-09-09 22:41:15,888 DEBUG | o.s.s.w.FilterChainProxy | anonymousUser | 91U89hqS96LB | /enduser/securityQuestions.do?clear=true at position 10 of 12 in additional filter chain; firing Filter: 'SessionManagementFilter'
2014-09-09 22:41:15,889 DEBUG | o.s.s.w.session.SessionManagementFilter | anonymousUser | 91U89hqS96LB | Requested session ID 0F7B56BA141C0A001C95180FE06BE864 is invalid.
2014-09-09 22:41:15,889 DEBUG | o.s.s.w.FilterChainProxy | anonymousUser | 91U89hqS96LB | /enduser/securityQuestions.do?clear=true at position 11 of 12 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
2014-09-09 22:41:15,890 DEBUG | o.s.s.w.FilterChainProxy | anonymousUser | 91U89hqS96LB | /enduser/securityQuestions.do?clear=true at position 12 of 12 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
2014-09-09 22:41:15,891 DEBUG | o.s.s.w.util.AntPathRequestMatcher | anonymousUser | 91U89hqS96LB | Checking match of request : '/enduser/securityquestions.do'; against '/admin/**'
2014-09-09 22:41:15,891 DEBUG | o.s.s.w.util.AntPathRequestMatcher | anonymousUser | 91U89hqS96LB | Checking match of request : '/enduser/securityquestions.do'; against '/system/**'
2014-09-09 22:41:15,892 DEBUG | o.s.s.w.util.AntPathRequestMatcher | anonymousUser | 91U89hqS96LB | Checking match of request : '/enduser/securityquestions.do'; against '/enduser/**'
2014-09-09 22:41:15,893 DEBUG | o.s.s.w.access.intercept.FilterSecurityInterceptor | anonymousUser | 91U89hqS96LB | Secure object: FilterInvocation: URL: /enduser/securityQuestions.do?clear=true; Attributes: [isAuthenticated()]
2014-09-09 22:41:15,893 DEBUG | o.s.s.w.access.intercept.FilterSecurityInterceptor | anonymousUser | 91U89hqS96LB | Previously Authenticated: o.s.s.authentication.AnonymousAuthenticationToken#6faab5ec: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: o.s.s.w.authentication.WebAuthenticationDetails#ffffc434: SessionId: null; Granted Authorities: ROLE_ANONYMOUS
2014-09-09 22:41:15,894 DEBUG | o.s.s.access.vote.AffirmativeBased | anonymousUser | 91U89hqS96LB | Voter: o.s.s.w.access.expression.WebExpressionVoter#1fb01f38, returned: -1
2014-09-09 22:41:15,895 WARN | o.s.s.access.event.LoggerListener | anonymousUser | 91U89hqS96LB | Security authorization failed due to: o.s.s.access.AccessDeniedException: Access is denied; authenticated principal: o.s.s.authentication.AnonymousAuthenticationToken#6faab5ec: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: o.s.s.w.authentication.WebAuthenticationDetails#ffffc434: SessionId: null; Granted Authorities: ROLE_ANONYMOUS; secure object: FilterInvocation: URL: /enduser/securityQuestions.do?clear=true; configuration attributes: [isAuthenticated()]
2014-09-09 22:41:15,896 DEBUG | o.s.s.w.access.ExceptionTranslationFilter | anonymousUser | 91U89hqS96LB | Access is denied (user is anonymous); redirecting to authentication entry point
o.s.s.access.AccessDeniedException: Access is denied
at o.s.s.access.vote.AffirmativeBased.decide(AffirmativeBased.java:83)
After keep trying for couple of minutes user is redirected to the securityQuestion page and below are the logs for successful redirect from index.do to securityquestions.do
2014-09-09 22:29:32,006 DEBUG | o.s.s.w.FilterChainProxy | | cPZ5kp4XKw3e | /j_spring_security_check at position 5 of 12 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
2014-09-09 22:29:32,007 DEBUG | o.s.s.w.authentication.UsernamePasswordAuthenticationFilter | | cPZ5kp4XKw3e | Request is to process authentication
2014-09-09 22:29:32,007 DEBUG | o.s.s.authentication.ProviderManager | | cPZ5kp4XKw3e | Authentication attempt using com.dc.apps.collaborationportal.security.service.CPDaoAuthenticationProvider
2014-09-09 22:29:32,078 DEBUG | o.s.s.w.authentication.UsernamePasswordAuthenticationFilter | | cPZ5kp4XKw3e | Authentication success. Updating SecurityContextHolder to contain: o.s.s.authentication.UsernamePasswordAuthenticationToken#79692524: Principal: o.s.s.core.userdetails.User#49520377: Username: test1#dc.com; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Not granted any authorities; Credentials: [PROTECTED]; Authenticated: true; Details: o.s.s.w.authentication.WebAuthenticationDetails#12afc: SessionId: 8822A6A448B6B75C997DF69C9B474DE6; Not granted any authorities
2014-09-09 22:29:32,296 DEBUG | o.s.s.w.DefaultRedirectStrategy | test1#dc.com | cPZ5kp4XKw3e | Redirecting to '/PP/enduser/securityQuestions.do?clear=true'
2014-09-09 22:29:32,297 DEBUG | o.s.s.w.context.HttpSessionSecurityContextRepository | test1#dc.com | cPZ5kp4XKw3e | SecurityContext stored to HttpSession: 'o.s.s.core.context.SecurityContextImpl#79692524: Authentication: o.s.s.authentication.UsernamePasswordAuthenticationToken#79692524: Principal: o.s.s.core.userdetails.User#49520377: Username: test1#dc.com; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Not granted any authorities; Credentials: [PROTECTED]; Authenticated: true; Details: o.s.s.w.authentication.WebAuthenticationDetails#12afc: SessionId: 8822A6A448B6B75C997DF69C9B474DE6; Not granted any authorities'
2014-09-09 22:29:32,298 DEBUG | o.s.s.w.context.SecurityContextPersistenceFilter | | cPZ5kp4XKw3e | SecurityContextHolder now cleared, as request processing completed
2014-09-09 22:29:33,309 DEBUG | o.s.s.w.FilterChainProxy | | 91U89hqS96LB | /enduser/securityQuestions.do?clear=true at position 1 of 12 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2014-09-09 22:29:33,309 DEBUG | o.s.s.w.context.HttpSessionSecurityContextRepository | | 91U89hqS96LB | Obtained a valid SecurityContext from SPRING_SECURITY_CONTEXT: 'o.s.s.core.context.SecurityContextImpl#79692524: Authentication: o.s.s.authentication.UsernamePasswordAuthenticationToken#79692524: Principal: o.s.s.core.userdetails.User#49520377: Username: test1#dc.com; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Not granted any authorities; Credentials: [PROTECTED]; Authenticated: true; Details: o.s.s.w.authentication.WebAuthenticationDetails#12afc: SessionId: 8822A6A448B6B75C997DF69C9B474DE6; Not granted any authorities'
2014-09-09 22:29:33,310 DEBUG | o.s.s.w.FilterChainProxy | test1#dc.com | 91U89hqS96LB | /enduser/securityQuestions.do?clear=true at position 2 of 12 in additional filter chain; firing Filter: 'WelcomePageRedirectFilter'
Created a new filter as below which overrides the default Tomcat JSESSIONID behaviour
public class HttpsCookieFilter implements Filter {
private static final Logger LOGGER = Logger.getInstance(HttpsCookieFilter.class);
#Override
public void destroy() {
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
ServletException {
final HttpServletRequest httpRequest = (HttpServletRequest) request;
final HttpServletResponse httpResponse = (HttpServletResponse) response;
final HttpSession session = httpRequest.getSession(false);
if (session != null) {
final Cookie sessionCookie = new Cookie("JSESSIONID", session.getId());
sessionCookie.setMaxAge(readCookieTimeoutfromProperties());
sessionCookie.setSecure(false);
sessionCookie.setPath(httpRequest.getContextPath());
httpResponse.addCookie(sessionCookie);
LOGGER.log(Level.DEBUG, "Session not null and setting SessionCookie --> " + sessionCookie.getValue()
+ "; SessionCookie Age --> " + sessionCookie.getMaxAge());
}
chain.doFilter(request, response);
}
#Override
public void init(FilterConfig arg0) throws ServletException {
}
private int readCookieTimeoutfromProperties() {
ResourceBundleMessageSource bean = new ResourceBundleMessageSource();
bean.setBasename("application-messages");
String tmeout = bean.getMessage("security.cookie.timeout", null, Locale.getDefault());
return Integer.parseInt(tmeout);
}
}
And invoking this filter prior to the springSecurityFilterChain in web.xml
<

loadUserByUsername being passed empty username

I am trying to implement an example from "Pro Spring Security" by Scarioni which implements a custom in memory user model (implementing the UserDetailsService interface) and custom expression handler. When I try to log in, the loadUserByUsername() method of my CustomInMemoryUserDetailsManager is passed a blank (not null) string for the username. This results in access denied. If I force the username to be that expected (admin), everything works fine including the custom expression handling.
Here is my security configuration:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<security:http auto-config="true" use-expressions="true" >
<security:expression-handler ref="expressionHandler" />
<security:intercept-url pattern="/admin/*" access="hasRole('ROLE_ADMIN') and hasIpAddress('127.0.0.1') and over18"/>
<security:remember-me key="terror-key" />
<security:form-login login-page="/custom_login"
authentication-failure-handler-ref="serverErrorHandler"
username-parameter="user_param" password-parameter="pass_param" />
</security:http>
<security:authentication-manager>
<security:authentication-provider user-service-ref="inMemoryUserServiceWithCustomUser" />
</security:authentication-manager>
<!-- Custom expression handler bean -->
<bean id="expressionHandler" class="com.apress.pss.terrormovies.security.CustomWebSecurityExpressionHandler"/>
<bean id="inMemoryUserServiceWithCustomUser"
class="com.apress.pss.terrormovies.spring.CustomInMemoryUserDetailsManager">
<constructor-arg>
<list>
<bean class="com.apress.pss.terrormovies.model.User">
<constructor-arg value="admin"/>
<constructor-arg value="admin"/>
<constructor-arg>
<list>
<bean class="org.springframework.security.core.authority.SimpleGrantedAuthority">
<constructor-arg value="ROLE_ADMIN"/>
</bean>
</list>
</constructor-arg>
<constructor-arg value="Scarioni"/>
<constructor-arg value="19"/>
</bean>
</list>
</constructor-arg>
</bean>
<bean id="logoutRedirectToAny"
class="org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler">
</bean>
<bean id="serverErrorHandler" class="com.apress.pss.terrormovies.security.ServerErrorFailureHandler"/>
</beans>
Here is my CustomInMemoryUserDetailsManager class:
package com.apress.pss.terrormovies.spring;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.apress.pss.terrormovies.model.User;
public class CustomInMemoryUserDetailsManager implements UserDetailsService {
private final Log logger = LogFactory.getLog(getClass());
private Map<String, User> users = new HashMap<String, User>();
public CustomInMemoryUserDetailsManager(Collection<User> users) {
for (User user : users) {
this.users.put(user.getUsername().toLowerCase(), user);
logger.debug("CustomInMemoryUserDetailsManager()- put username: " +
user.getUsername() + " last name: " + user.getLastName() + " authority: " +
user.getAuthorities());
}
}
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// Test - force user name to that expected
//username = "admin";
if (username.equals("")) logger.debug("loadUserByUsername()- username is blank!!!");
logger.debug("loadUserByUsername()- username: " + username);
User user = users.get(username.toLowerCase());
if (user == null) {
throw new UsernameNotFoundException(username);
}
logger.debug("loadUserByUsername()- found " + user.getUsername());
User userNew = new User(user.getUsername(), user.getPassword(),
user.getAuthorities(), user.getLastName(), user.getAge());
return userNew;
}
}
I turned on Spring debugging and got a very large log, here is what I think is the relevent part from the point of logging to j_spring_security_check:
:28,785 DEBUG main DispatcherServlet:130 - Servlet 'terrormovies' configured successfully
08:29:48,058 DEBUG qtp1624348237-15 FilterChainProxy:337 - /admin/movies at position 1 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
08:29:48,072 DEBUG qtp1624348237-15 HttpSessionSecurityContextRepository:127 - No HttpSession currently exists
08:29:48,085 DEBUG qtp1624348237-15 HttpSessionSecurityContextRepository:85 - No SecurityContext was available from the HttpSession: null. A new one will be created.
08:29:48,120 DEBUG qtp1624348237-15 FilterChainProxy:337 - /admin/movies at position 2 of 11 in additional filter chain; firing Filter: 'LogoutFilter'
08:29:48,120 DEBUG qtp1624348237-15 FilterChainProxy:337 - /admin/movies at position 3 of 11 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
08:29:48,120 DEBUG qtp1624348237-15 FilterChainProxy:337 - /admin/movies at position 4 of 11 in additional filter chain; firing Filter: 'BasicAuthenticationFilter'
08:29:48,121 DEBUG qtp1624348237-15 FilterChainProxy:337 - /admin/movies at position 5 of 11 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
08:29:48,121 DEBUG qtp1624348237-15 FilterChainProxy:337 - /admin/movies at position 6 of 11 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
08:29:48,122 DEBUG qtp1624348237-15 FilterChainProxy:337 - /admin/movies at position 7 of 11 in additional filter chain; firing Filter: 'RememberMeAuthenticationFilter'
08:29:48,123 DEBUG qtp1624348237-15 FilterChainProxy:337 - /admin/movies at position 8 of 11 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
08:29:48,124 DEBUG qtp1624348237-15 AnonymousAuthenticationFilter:102 - Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken#9055e4a6: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS'
08:29:48,125 DEBUG qtp1624348237-15 FilterChainProxy:337 - /admin/movies at position 9 of 11 in additional filter chain; firing Filter: 'SessionManagementFilter'
08:29:48,125 DEBUG qtp1624348237-15 SessionManagementFilter:92 - Requested session ID ncic677387xfiq2ciohmau1 is invalid.
08:29:48,126 DEBUG qtp1624348237-15 FilterChainProxy:337 - /admin/movies at position 10 of 11 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
08:29:48,126 DEBUG qtp1624348237-15 FilterChainProxy:337 - /admin/movies at position 11 of 11 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
08:29:48,126 DEBUG qtp1624348237-15 AntPathRequestMatcher:103 - Checking match of request : '/admin/movies'; against '/admin/*'
08:29:48,127 DEBUG qtp1624348237-15 FilterSecurityInterceptor:194 - Secure object: FilterInvocation: URL: /admin/movies; Attributes: [hasRole('ROLE_ADMIN') and hasIpAddress('127.0.0.1') and over18]
08:29:48,127 DEBUG qtp1624348237-15 FilterSecurityInterceptor:310 - Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken#9055e4a6: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS
08:29:48,129 DEBUG qtp1624348237-15 CustomWebSecurityExpressionRoot:22 - CustomWebSecurityExpressionRoot()- call
08:29:48,154 DEBUG qtp1624348237-15 AffirmativeBased:65 - Voter: org.springframework.security.web.access.expression.WebExpressionVoter#35333295, returned: -1
08:29:48,157 DEBUG qtp1624348237-15 ExceptionTranslationFilter:165 - Access is denied(user is anonymous); redirecting to authentication entry point
org.springframework.security.access.AccessDeniedException: Access is denied at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:83)
at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:206)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:115)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
...
On initialization you can see the user being correctly entered into the users HashMap in the log:
08:29:25,912 DEBUG main CustomInMemoryUserDetailsManager:26 - CustomInMemoryUserDetailsManager()- put username: admin last name: Scarioni authority: [ROLE_ADMIN]
I noticed the user is coming in as anonymous, I'm not sure why. Any help would be greatly appreciated.
Thanks
mike

An Authentication object was not found in the SecurityContext - Spring 3.2.2

I'm trying to invoke a protected method from a class that implements the ApplicationListener<AuthenticationSuccessEvent> interface on successful login (Spring 3.2.2 and Spring Security 3.2.0 M1). This is my previous question.
The application runs under the following environment.
Spring 3.2.2
Spring Security 3.2.0
JPA 2.0
JSF 2.1.9
MySQL 5.6.11
JDK-7u11
NetBeans 7.2.1
I have added the following libraries related to Spring security to the classpath.
spring-security-core-3.2.0.M1.jar
spring-security-config-3.2.0.M1.jar
spring-security-web-3.2.0.M1.jar
The class that implements ApplicationListener<AuthenticationSuccessEvent> is as follows.
package loginsuccesshandler;
import admin.dao.service.StateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.stereotype.Service;
#Service
public final class AuthSuccessHandler implements ApplicationListener<AuthenticationSuccessEvent>
{
#Autowired
private StateService stateService;
#Override
public void onApplicationEvent(AuthenticationSuccessEvent event)
{
System.out.println(event.getAuthentication());
System.out.println("rowCount = "+stateService.rowCount());
}
}
This prevents a user from being logged in even with correct credentials with the following message (it is just an example. Counting the number of states upon successful authentication is not required at all).
An Authentication object was not found in the SecurityContext
The event is raised. The first statement inside the onApplicationEvent() method displays the following.
org.springframework.security.authentication.UsernamePasswordAuthenticationToken#45264a59: Principal: org.springframework.security.core.userdetails.User#586034f:Username: admin;
Password: [PROTECTED];
Enabled: true;
AccountNonExpired: true;
credentialsNonExpired: true;
AccountNonLocked: true;
Granted Authorities: ROLE_ADMIN;
Credentials: [PROTECTED];
Authenticated: true;
Details: org.springframework.security.web.authentication.WebAuthenticationDetails#380f4: RemoteIpAddress: 127.0.0.1;
SessionId: 88777A678DC5BB0272F84CA4BC61FAF2;
Granted Authorities: ROLE_ADMIN
So it appears that the user is authenticated and the authentication object is available.
My springSecurity.xml file simply looks like the following.
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<http pattern="/utility/Login.jsf*" security="none"/>
<debug/>
<http auto-config='true' use-expressions="true" disable-url-rewriting="true">
<session-management session-fixation-protection="newSession">
<concurrency-control max-sessions="1" error-if-maximum-exceeded="true" />
</session-management>
<intercept-url pattern="/admin_side/**" access="hasRole('ROLE_ADMIN')" requires-channel="any"/>
<intercept-url pattern="/utility/Login.jsf" access="permitAll" requires-channel="any"/>
<http-basic />
<anonymous />
<form-login login-processing-url="/j_spring_security_check" login-page="/utility/Login.jsf" authentication-success-handler-ref="loginSuccessHandler" authentication-failure-handler-ref="authenticationFailureHandler"/>
<logout logout-success-url="/utility/Login.jsf" invalidate-session="true" delete-cookies="JSESSIONID"/>
</http>
<authentication-manager>
<authentication-provider>
<jdbc-user-service data-source-ref="dataSource"
users-by-username-query="select email_id, password, enabled from user_table where lower(email_id)=lower(?)"
authorities-by-username-query="select ut.email_id, ur.authority from user_table ut, user_roles ur where ut.user_id=ur.user_id and lower(ut.email_id)=lower(?)"/>
</authentication-provider>
</authentication-manager>
<beans:bean id="loginSuccessHandler" class="loginsuccesshandler.LoginSuccessHandler"/>
<beans:bean id="authenticationFailureHandler" class="loginsuccesshandler.AuthenticationFailureHandler" />
<global-method-security secured-annotations="enabled" pre-post-annotations="enabled" proxy-target-class="false">
<protect-pointcut expression="execution(* admin.dao.*.*(..))" access="ROLE_ADMIN"/>
</global-method-security>
</beans:beans>
The Spring security works fine, when the following lines of XML is omitted from the spring-security.xml file.
<global-method-security secured-annotations="enabled" proxy-target-class="false">
<protect-pointcut expression="execution(* admin.dao.*.*(..))" access="ROLE_ADMIN"/>
</global-method-security>
Can a protected method (with method security applied) be invoked from a class implementing the ApplicationListener<AuthenticationSuccessEvent> interface? If yes, then what is missing in my case? I have clicked thousands of links so far but couldn't find a single clue.
The application-context.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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<context:component-scan base-package="admin.mangedbean loginsuccesshandler" use-default-filters="false">
<context:include-filter expression="org.springframework.stereotype.Controller" type="annotation"/>
<context:include-filter expression="org.springframework.web.bind.annotation.ControllerAdvice" type="annotation"/>
</context:component-scan>
<mvc:annotation-driven/>
<context:annotation-config/>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>
<bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory" >
<property name="jpaProperties">
<props>
<prop key="hibernate.enable_lazy_load_no_trans">true</prop>
</props>
</property>
<property name="jpaPropertyMap">
<map>
<entry key="eclipselink.weaving" value="false"/>
</map>
</property>
<property name="loadTimeWeaver">
<bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="java:comp/env/jdbc/social_networking"/>
</bean>
<!--The bean shown in the beginning is configured here-->
<bean id="authSuccessHandler" class="loginsuccesshandler.AuthSuccessHandler"/>
<bean id="testService" class="admin.dao.TestDAO"/>
<bean id="stateService" class="admin.dao.StateDAO"/>
<bean id="sharableService" class="admin.dao.SharableDAO"/>
</beans>
The web.xml file.
<?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
/WEB-INF/spring-security.xml
</param-value>
</context-param>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<!--<param-value>Development</param-value>-->
<param-value>Production</param-value>
</context-param>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/log4j.properties</param-value>
</context-param>
<context-param>
<param-name>log4jExposeWebAppRoot</param-name>
<param-value>false</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>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<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>*.jsf</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<security-constraint>
<display-name>Restrict direct access to XHTML files</display-name>
<web-resource-collection>
<web-resource-name>XHTML files</web-resource-name>
<url-pattern>*.xhtml</url-pattern>
</web-resource-collection>
<auth-constraint />
</security-constraint>
<session-config>
<session-timeout>
120
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>/utility/Login.jsf</welcome-file>
</welcome-file-list>
<resource-ref>
<res-ref-name>jdbc/social_networking</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
</web-app>
The debug information can be seen below, when an attempt is made to login which ultimately fails.
DEBUG [http-apr-8080-exec-55] (AntPathRequestMatcher.java:116) - Checking match of request : '/j_spring_security_check'; against '/utility/login.jsf*'
DEBUG [http-apr-8080-exec-55] (AntPathRequestMatcher.java:116) - Checking match of request : '/j_spring_security_check'; against '/utility/login.jsf*'
DEBUG [http-apr-8080-exec-55] (FilterChainProxy.java:337) - /j_spring_security_check at position 1 of 13 in additional filter chain; firing Filter: 'ChannelProcessingFilter'
DEBUG [http-apr-8080-exec-55] (AntPathRequestMatcher.java:116) - Checking match of request : '/j_spring_security_check'; against '/admin_side/**'
DEBUG [http-apr-8080-exec-55] (AntPathRequestMatcher.java:116) - Checking match of request : '/j_spring_security_check'; against '/utility/login.jsf'
DEBUG [http-apr-8080-exec-55] (FilterChainProxy.java:337) - /j_spring_security_check at position 2 of 13 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
DEBUG [http-apr-8080-exec-55] (HttpSessionSecurityContextRepository.java:139) - HttpSession returned null object for SPRING_SECURITY_CONTEXT
DEBUG [http-apr-8080-exec-55] (HttpSessionSecurityContextRepository.java:85) - No SecurityContext was available from the HttpSession: org.apache.catalina.session.StandardSessionFacade#1103da5. A new one will be created.
DEBUG [http-apr-8080-exec-55] (FilterChainProxy.java:337) - /j_spring_security_check at position 3 of 13 in additional filter chain; firing Filter: 'ConcurrentSessionFilter'
DEBUG [http-apr-8080-exec-55] (FilterChainProxy.java:337) - /j_spring_security_check at position 4 of 13 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
DEBUG [http-apr-8080-exec-55] (FilterChainProxy.java:337) - /j_spring_security_check at position 5 of 13 in additional filter chain; firing Filter: 'LogoutFilter'
DEBUG [http-apr-8080-exec-55] (FilterChainProxy.java:337) - /j_spring_security_check at position 6 of 13 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
DEBUG [http-apr-8080-exec-55] (AbstractAuthenticationProcessingFilter.java:189) - Request is to process authentication
DEBUG [http-apr-8080-exec-55] (ProviderManager.java:152) - Authentication attempt using org.springframework.security.authentication.dao.DaoAuthenticationProvider
DEBUG [http-apr-8080-exec-55] (JdbcTemplate.java:637) - Executing prepared SQL query
DEBUG [http-apr-8080-exec-55] (JdbcTemplate.java:572) - Executing prepared SQL statement [select email_id, password, enabled from user_table where lower(email_id)=lower(?)]
DEBUG [http-apr-8080-exec-55] (DataSourceUtils.java:110) - Fetching JDBC Connection from DataSource
DEBUG [http-apr-8080-exec-55] (DataSourceUtils.java:327) - Returning JDBC Connection to DataSource
DEBUG [http-apr-8080-exec-55] (JdbcTemplate.java:637) - Executing prepared SQL query
DEBUG [http-apr-8080-exec-55] (JdbcTemplate.java:572) - Executing prepared SQL statement [select ut.email_id, ur.authority from user_table ut, user_roles ur where ut.user_id=ur.user_id and lower(ut.email_id)=lower(?)]
DEBUG [http-apr-8080-exec-55] (DataSourceUtils.java:110) - Fetching JDBC Connection from DataSource
DEBUG [http-apr-8080-exec-55] (DataSourceUtils.java:327) - Returning JDBC Connection to DataSource
DEBUG [http-apr-8080-exec-55] (AbstractBeanFactory.java:246) - Returning cached instance of singleton bean 'authSuccessHandler'
DEBUG [http-apr-8080-exec-55] (AbstractBeanFactory.java:246) - Returning cached instance of singleton bean 'org.springframework.security.core.session.SessionRegistryImpl#0'
DEBUG [http-apr-8080-exec-55] (AbstractFallbackTransactionAttributeSource.java:106) - Adding transactional method 'rowCount' with attribute: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
DEBUG [http-apr-8080-exec-55] (DelegatingMethodSecurityMetadataSource.java:65) - Caching method [CacheKey[admin.dao.StateDAO; public abstract java.lang.Long admin.dao.service.StateService.rowCount()]] with attributes [ROLE_ADMIN]
DEBUG [http-apr-8080-exec-55] (AbstractBeanFactory.java:246) - Returning cached instance of singleton bean 'transactionManager'
DEBUG [http-apr-8080-exec-55] (AbstractPlatformTransactionManager.java:366) - Creating new transaction with name [admin.dao.StateDAO.rowCount]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''
DEBUG [http-apr-8080-exec-55] (JpaTransactionManager.java:369) - Opened new EntityManager [org.hibernate.ejb.EntityManagerImpl#84ff11] for JPA transaction
DEBUG [http-apr-8080-exec-55] (JpaTransactionManager.java:408) - Not exposing JPA transaction [org.hibernate.ejb.EntityManagerImpl#84ff11] as JDBC transaction because JpaDialect [org.springframework.orm.jpa.DefaultJpaDialect#d9dbb8] does not support JDBC Connection retrieval
DEBUG [http-apr-8080-exec-55] (AbstractSecurityInterceptor.java:194) - Secure object: ReflectiveMethodInvocation: public abstract java.lang.Long admin.dao.service.StateService.rowCount(); target is of class [admin.dao.StateDAO]; Attributes: [ROLE_ADMIN]
DEBUG [http-apr-8080-exec-55] (AbstractBeanFactory.java:246) - Returning cached instance of singleton bean 'authSuccessHandler'
DEBUG [http-apr-8080-exec-55] (AbstractBeanFactory.java:246) - Returning cached instance of singleton bean 'org.springframework.security.core.session.SessionRegistryImpl#0'
DEBUG [http-apr-8080-exec-55] (AbstractPlatformTransactionManager.java:844) - Initiating transaction rollback
DEBUG [http-apr-8080-exec-55] (JpaTransactionManager.java:534) - Rolling back JPA transaction on EntityManager [org.hibernate.ejb.EntityManagerImpl#84ff11]
DEBUG [http-apr-8080-exec-55] (JpaTransactionManager.java:594) - Closing JPA EntityManager [org.hibernate.ejb.EntityManagerImpl#84ff11] after transaction
DEBUG [http-apr-8080-exec-55] (EntityManagerFactoryUtils.java:338) - Closing JPA EntityManager
DEBUG [http-apr-8080-exec-55] (AbstractAuthenticationProcessingFilter.java:346) - Authentication request failed: org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext
DEBUG [http-apr-8080-exec-55] (AbstractAuthenticationProcessingFilter.java:347) - Updated SecurityContextHolder to contain null Authentication
DEBUG [http-apr-8080-exec-55] (AbstractAuthenticationProcessingFilter.java:348) - Delegating to authentication failure handler loginsuccesshandler.AuthenticationFailureHandler#14883a3
DEBUG [http-apr-8080-exec-55] (DefaultRedirectStrategy.java:36) - Redirecting to '/SocialNetworking/utility/Login.jsf'
DEBUG [http-apr-8080-exec-55] (HttpSessionSecurityContextRepository.java:269) - SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
DEBUG [http-apr-8080-exec-55] (SecurityContextPersistenceFilter.java:97) - SecurityContextHolder now cleared, as request processing completed
DEBUG [http-apr-8080-exec-49] (AntPathRequestMatcher.java:116) - Checking match of request : '/utility/login.jsf'; against '/utility/login.jsf*'
DEBUG [http-apr-8080-exec-49] (AntPathRequestMatcher.java:116) - Checking match of request : '/utility/login.jsf'; against '/utility/login.jsf*'
DEBUG [http-apr-8080-exec-49] (FilterChainProxy.java:180) - /utility/Login.jsf has an empty filter list
The last thing:
When I give up this bean and unregister from the application-context.xml file, the login is made successfully but the following information can be seen on the server console.
DEBUG [http-apr-8080-exec-165] (HttpSessionSecurityContextRepository.java:139) - HttpSession returned null object for SPRING_SECURITY_CONTEXT
DEBUG [http-apr-8080-exec-165] (HttpSessionSecurityContextRepository.java:85) - No SecurityContext was available from the HttpSession: org.apache.catalina.session.StandardSessionFacade#b910c1. A new one will be created.
The security's authorization check part gets the authenticated object from SecurityContext, which will be set when a request gets through the spring security filter. My assumption here is that soon after the login this is not being set. You probably can use a hack as given below to set the value.
try {
SecurityContext ctx = SecurityContextHolder.createEmptyContext();
SecurityContextHolder.setContext(ctx);
ctx.setAuthentication(event.getAuthentication());
//Do what ever you want to do
} finally {
SecurityContextHolder.clearContext();
}
Update:
Also you can have a look at the InteractiveAuthenticationSuccessEvent which will be called once the SecurityContext is set.
This could also happens if you put a #PreAuthorize or #PostAuthorize in a Bean in creation. I would recommend to move such annotations to methods of interest.
As pointed already by #Arun P Johny the root cause of the problem is that at the moment when AuthenticationSuccessEvent is processed SecurityContextHolder is not populated by Authentication object. So any declarative authorization checks (that must get user rights from SecurityContextHolder) will not work. I give you another idea how to solve this problem. There are two ways how you can run your custom code immidiately after successful authentication:
Listen to AuthenticationSuccessEvent
Provide your custom AuthenticationSuccessHandler implementation.
AuthenticationSuccessHandler has one important advantage over first way: SecurityContextHolder will be already populated. So just move your stateService.rowCount() call into loginsuccesshandler.LoginSuccessHandler#onAuthenticationSuccess(...) method and the problem will go away.
There is similar issue. I added listener as given here
https://stackoverflow.com/questions/3145936/spring-security-j-spring-security-logout-problem
It worked for me adding below lines to web.xml.
Posting it very late, should help someone looking for answer.
<listener>
<listener-class> org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
</listener>
I encountered the same error while using SpringBoot 2.1.4, along with Spring Security 5 (I believe). After one day of trying everything that Google had to offer, I discovered the cause of error in my case. I had a setup of micro-services, with the Auth server being different from the Resource Server. I had the following lines in my application.yml which prevented 'auto-configuration' despite of having included dependencies spring-boot-starter-security, spring-security-oauth2 and spring-security-jwt. I had included the following in the properties (during development) which caused the error.
spring:
autoconfigure:
exclude: org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration
Commenting it out solved it for me.
#spring:
# autoconfigure:
# exclude: org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration
Hope, it helps someone.
For me, the problem was a ContextRefreshedEvent handler. I was doing some data initilization but at that point in the application the Authentication had not been set. It was a catch 22 since the system needed an authentication to authorize and it needed authorization to get the authentication details :). I ended up loosening the authorization from a class level to a method level.
My issue was that I needed to properly disable security and implement my own preAuthorization. Unlike the OP, I was trying to disable authentication altogether and implement my own solution.
#Configuration
#EnableWebSecurity
public class CustomWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity.csrf().disable().authorizeRequests().antMatchers("/**").permitAll();
}
}
I had the same problem when and I solved it by using the following annotation :
#EnableAutoConfiguration(exclude = {
SecurityAutoConfiguration.class
})
public class Application {...}
I think the behavior is the same as what Abhishek explained
This error can also be got if you use Content-Type: application/json instead of Content-Type:application/x-www-form-urlencoded
In my case i simply forgot to initialize spring security, this can be done by extending AbstractSecurityWebApplicationInitializer when you use an empty web.xml file.

Spring security works with access="ROLE_USER" but not with EL

I'm learning to use Spring Security and I've integrated it in a web application. I'm using Spring and Spring Security version 3.1.2.
If I specify access="ROLE_USER" in the security configuration, the authentication, works correctly, that is I first receive a 401 and after logging in, I'm able to access the resources.
<http>
<http-basic />
<logout />
<intercept-url
pattern="/exports/**"
access="ROLE_USER" />
</http>
However, if I switch to EL, my check doesn't work anymore:
<http use-expressions="true">
<http-basic />
<logout />
<intercept-url
pattern="/exports/**"
access="hasRole('USER')" />
</http>
I thought that those two configuration were equivalent, but the second one is not authorising to view the resource (403 error).
Looking at the logs:
DEBUG org.springframework.security.web.access.intercept.FilterSecurityInterceptor - Previously Authenticated: org.springframework.security.authentication.UsernamePasswordAuthenticationToken#844f42c6: Principal: org.springframework.security.core.userdetails.User#c052d588: Username: test; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_USER; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Granted Authorities: ROLE_USER
DEBUG org.springframework.security.access.vote.AffirmativeBased - Voter: org.springframework.security.web.access.expression.WebExpressionVoter#1a15597, returned: -1
DEBUG org.springframework.security.web.access.ExceptionTranslationFilter - Access is denied (user is not anonymous); delegating to AccessDeniedHandler
If I understand right, the WebExpressionVoter is voting against me, despite the authentication worked.
What am I missing?
The solution was simple: just add ROLE_ also in hasRole(), such as:
access="hasRole('ROLE_USER')"
I got mislead by an example in section 16.2 of the manual.

Resources