I am working with Spring MVC 4 and Spring Security 3.1 on a web application. I have a requirement where I need to update user's detail when user logs in and whenever he logs out. I searched a lot here and found answers that explained use of HttpSessionListener and HttpSessionPublishEvent of Spring. I also understood that SecurityContextHolder.getContext().getAuthentication() and then getting the principal object wouldn;t work in these listeners. But somebody exaplained to get it through
session.getAttribute("SPRING_SECURITY_CONTEXT")
However I am not able to access
session.getAttribute("SPRING_SECURITY_CONTEXT")
when user logs in so that I can get authentication and principal objects. In both above implementations I get this attribute as null whenever sessionCreated/sessionDestroyed event is called.
My login page is rendered using a action
http://localhost:8081/myapp/auth/showLogin
and then I login using form login.
I am using custom UserDetails object as follows :.
public class SecurityContext {
public static ChatterUserDetails getCurrentUser(){
Object principal = SecurityContextHolder.getContext().getAuthentication().
getPrincipal();
if(principal instanceof MyUserDetails){
return (MyUserDetails) principal;
}
MyUserDetails anonymousJkWebUserDetails = new MyUserDetails("anonymous","anonymous",
new ArrayList<GrantedAuthority>());
anonymousJkWebUserDetails.setAnonymous(true);
return anonymousJkWebUserDetails;
}
}
and security.xml is as follows (only relevant sections ) :
<http use-expressions="true">
<intercept-url pattern="/auth/showLogin" access="permitAll()"></intercept-url>
....
</http>
<form-login login-page="/auth/showLogin" always-use-default-target="true"
default-target-url="/auth/home" authentication-failure-url="/auth/showLogin?error=1"
login-processing-url="/auth/login" password-parameter="userPassword"
username-parameter="userId" />
<logout logout-success-url="http://${email.link.host}" logout-url="/auth/logout" delete-cookies="JSESSIONID" invalidate-session="true"></logout>