Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Spring Security manage SecurityContext in a thread across web application requests?

In SpringSecurity it has a class name SecurityContextHolder and its spec: 'Associates a given SecurityContext with the current execution thread.' With web application whenever a request comes to server then Spring also reload and set SecurityContext of that request in SecurityContextHolder for its thread?

like image 774
Martin Avatar asked Aug 24 '11 09:08

Martin


2 Answers

Yes, the SecurityContextPersistenceFilter takes care of this. By default it locates the SecurityContext in the HttpSession and binds it to the thread via the SecurityContextHolder. When the request is finished processing it does the reverse - it takes the SecurityContext from the thread and puts it in the session.

From the Javadoc:

Populates the SecurityContextHolder with information obtained from the configured SecurityContextRepository prior to the request and stores it back in the repository once the request has completed and clearing the context holder. By default it uses an HttpSessionSecurityContextRepository.

like image 61
sourcedelica Avatar answered Oct 23 '22 14:10

sourcedelica


With web application whenever a request comes to server then Spring also reload and set SecurityContext of that request in SecurityContextHolder for its thread?

Basically yes.

The default behavior of SecurityContextHolder.getInstance() is to return a SecurityContextHolder instance that it stored as a thread-local of the current thread. (This is only the default mechanism. You can use a different strategy for locating the SecurityContextHolder by calling SecurityContextHolder.setStrategemName())

A SpringSecurity filters ensure that the request's SecurityContextHolder (however it is located) is loaded with the request credentials at the start and that the holder is cleared at the end of request processing.

like image 25
Stephen C Avatar answered Oct 23 '22 14:10

Stephen C