Adam Walczak - WALCZAK.IT (Migrated from SEC-2481) said:

At first glance this seams simple - you can find this code everywhere on the net:

UsernamePasswordAuthenticationToken authReq = new UsernamePasswordAuthenticationToken(c.getUsername(), c.getPassword());
authReq.setDetails(new WebAuthenticationDetails(reqAttrs.getRequest()));
Authentication authRes = getAuthenticationManager().authenticate(authReq);
SecurityContext context = SecurityContextHolder.getContext();
context.setAuthentication(authRes);

you put it in a controller method and its seams to work at first - your secured code in the same request gets executed. Bah ! you are even able to open another web page which will recognize you authentication properly.

However on the next page (after the first one) your authentication is lost... mind boggling... isn't it ? It works like this all the time. Event if you start putting the SecurityContext to the HTTP session your self. You debug and know its there in the session but to your surprise SecurityContextHolder.getContext().getAuthentication() returns null.

After a whole day of hacking and googling you find one line of code:

authReq.setDetails(new WebAuthenticationDetails(reqAttrs.getRequest()));

at first it seamed to work but the result just turned out to be totally random. Once you get the Authentication object, once you don't...

Comment From: MartinKnopf

This issue is old. What about closing it? If it was a real bug, it would return.

Comment From: rwinch

If you want the SecurityContext to persist, then you must also save it in the SecurityContextRepository.