Search code examples
linuxspring-bootjwtwarspring-security-oauth2

Spring Security getprincipal() method returns string (Username) in place of class UserDetails


We are using Spring-boot 2.0.5 with JWT Token

SecurityContextHolder.getContext().getAuthentication().getPrincipal() returning String (Username) in place of CustomUserDetails Object which is implemented UserDetails class in WAR file only.

This issue only replicates occasionally most of the time the code is working perfectly

The below mention is the only custom filter we are using and it is called after FilterSecurityInterceptor Filter

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    CustomHttpServletRequestWrapper request = new CustomHttpServletRequestWrapper((HttpServletRequest) req);
    if(request!=null && request.getHeader("Authorization")!=null && request.getHeader("Authorization").length()>7) {

        CustomUserDetails user = (CustomUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
}
}

It should be returning user detail object


Solution

  • in our case, there were two Bean with the same name which was causing the issue