I have been working on application that is using spring security. I am quite new to spring security and ended up with problem similar to this and this. But it is a bit different.
I do manual authentication this way:
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(username, password);
Authentication authentication = this.authenticationProvider.authenticate(token);
SecurityContextHolder.getContext().setAuthentication(authentication);
When the page loads everything seems OK. But, when I navigate around application it seems that I loose my SecurityContext. (I have status bar showing user name if user is logged in)
I get my context this way:
SecurityContextHolder.getContext()
What is more the context is not lost entirely sometimes it loads correctly, after some incorrect loads. It seems that I have several contexts in one session ( I have HttpSessionListener and sessionCreated fires only once). I tried printing out context's objects hashes and noticed that there are several different hashes repeating. Only one is with my connected user the others are not.
So I assume that there are several context's in one session (if this is even possible). I hope I explained everything clearly. I would be grateful if anybody could provide me with some help.
At last i did it! Marcel Stör answer did help me to look for correct keewords and so on. Thank you.
The problem was that I was setting SecurityContext in bean that was not aware of Security filter chain. It was called on @PostConstruct and it was not right.
What I really needed was PRE_AUTH_FILTER and proper Spring security configuration. So PRE_AUTH_FILTER is in SpringSecurity filter chain puts authentication object correctly.