Monday, June 16, 2025
HomeJavaWhat's SecurityContext and SecurityContextHolder in Spring Safety? Instance Tutorial

What’s SecurityContext and SecurityContextHolder in Spring Safety? Instance Tutorial


The SecurityContext and SecurityContextHolder are two basic courses of Spring Safety. The SecurityContext is used to retailer the main points of the at the moment authenticated person, often known as a precept. So, if you must get the username or every other person particulars, it’s good to get this SecurityContext first. The SecurityContextHolder is a helper class, which offers entry to the safety context. By default, it makes use of a ThreadLocal object to retailer safety context, which implies that the safety context is at all times out there to strategies in the identical thread of execution, even in the event you do not move the SecurityContext object round. Don’t fret concerning the ThreadLocal reminiscence leak in net software although, Spring Safety takes care of cleansing ThreadLocal.

Btw, that is not the one method a SecurityContextHolder can retailer present SecurityContext, it may be configured with a technique on startup to specify how you’d the context to be saved. For instance, you need to use SecurityContextHolder.MODE_GLOBAL technique for a standalone software.

The important thing factor to be taught is how do you get the SecurityContext from the SecurityContextHolder? after which retrieving present person particulars from that? For instance, if you wish to know the username of the at the moment logged-in person then how do you get that in Spring safety?

With the intention to get the present username, you first want a SecurityContext, which is obtained from SecurityContextHolder. This SecurityContext preserve the person particulars in an Authentication object, which might be obtained by calling the getAuthentication() technique.

As soon as you bought the Authentication object, you possibly can both solid it into UserDetails or use it as it’s. The UserDetails object is the one Spring Safety makes use of to maintain user-related data.

The right way to get the present logged-in Username in Spring Safety

Right here is the code to get the safety context in Spring safety and acquire the identify of the at the moment logged-in person:

Object principal = SecurityContextHolder.getContext()
                                        .getAuthentication()
                                        .getPrincipal();

if (principal instanceof UserDetails) {
  String username = ((UserDetails)principal).getUsername();
} else {
  String username = principal.toString();
}

The article returned by getContext() is an occasion of the SecurityContext interface. That is the thing that’s saved in thread-local storage.

The getPrincipal() technique usually returns the UserDetails object in Spring Safety, which comprises all the main points of the at the moment logged-in person. 

What is spring spring context and filter

Anyway, in the event you look nearer, you’ll find that this isn’t actually a pleasant code after we take into consideration Spring and dependency injection. So in the event you ever have to know present logged-in person particulars like,  in Spring MVC controller, I recommend you declare a dependency and let Spring present you the Principal object, slightly you querying for them and create a tightly coupled system.

Right here is an instance of that

import java.safety.Principal;
import org.springframework.stereotype.Controller;
import org.springframework.net.bind.annotation.RequestMapping;
import org.springframework.net.bind.annotation.RequestMethod;
import org.springframework.net.bind.annotation.ResponseBody;

@Controller
public class MVCController {

  @RequestMapping(worth = "/username", technique = RequestMethod.GET)
  @ResponseBody
  public String currentUserName(Principal principal) {
     return principal.getName();
  }

}

Alternatively, you may also ask for an Authentication object as an alternative of a Principal object as proven under:

import org.springframework.safety.core.Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.net.bind.annotation.RequestMapping;
import org.springframework.net.bind.annotation.RequestMethod;
import org.springframework.net.bind.annotation.ResponseBody;

@Controller
public class SpringMVCController {

  @RequestMapping(worth = "/username", technique = RequestMethod.GET)
  @ResponseBody
  public String currentUserName(Authentication authentication) {
     return authentication.getName();
  }
}

If you wish to know extra methods, you may also see my submit about 3 methods to get the present username in Spring Safety, the place I’ve mentioned a few extra methods to retrieve the present username within the Spring MVC controller.

That is all about what’s safety context in Spring safety and how one can receive a SecurityContext from SecurityContextHolder class. These are a few of the basic courses, therefore you have to be acquainted with them.

The storage half i.e. SecurityContext is saved in ThreadLocal is non-obligatory, but it surely’s additionally good to know the element. Simply bear in mind, in the event you ever want person particulars e.g. username and many others, you higher ask for Principal or Authentication object in Spring MVC controller, slightly than utilizing SecurityContextHolder to acquire them.

Different Spring Safety Articles and Assets chances are you’ll like:

  • 15 Spring Boot Interview Questions with Solutions (questions)
  • Prime 5 Programs to be taught Spring in depth (programs)
  • Official Spring Safety Documentation (docs)
  • Prime 5 Spring Boot Options Java developer ought to know (options)
  • 10 Free Programs to be taught Spring Boot for Rookies (free programs)
  • 21+ Spring MVC Interview Questions for Java builders (Questions)
  • Prime 5 Programs to be taught Microservices in Java (programs)
  • The right way to Crack Spring Certification for Java builders (certification)
  • 10 Superior Spring Boot Programs for Java builders (programs)
  • The right way to get a ServletContext object within the Spring controller? (instance)
  • Prime 5 Programs to be taught Spring Boot in-depth (programs)
  • The right way to change the port of tomcat in Spring boot (tutorial)
  • Prime 5 Books to be taught Spring Boot and Spring Cloud (books)
  • What’s the default bean scope within the Spring MVC framework? (reply)
  • Prime 5 Programs to be taught Spring Cloud for Java builders (programs)
  • 5 Finest Assets for Spring Certification (assets) 



RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments