문제

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.

도움이 되었습니까?

해결책 2

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.

다른 팁

For what you're doing the context needs to be bound to the current thread. Because, when you call

SecurityContextHolder.getContext()

the context from a ThreadLocal store is returned. Make sure the context is bound to your current thread with each request (can't tell more as you don't describe how you're doing that).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top