Issue
I need to get a UserDetails in servlet filter. So I'm getting it from SecurityContextHolder.getContext().getAuthentication() like this -
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws ServletException, IOException {
UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication()
.getPrincipal();
...
}
Locally the user is fetched from the Security context, but when deploying the app to GKE the SecurityContextHolder.getContext().getAuthentication() is null.
I've tried to configure SecurityContextHolder to MODE_INHERITABLETHREADLOCAL like this, but it didn't help
@Configuration
public class SecurityContextHolderConfig {
public SecurityContextHolderConfig() {
SecurityContextHolder.setStrategyName(SecurityContextHolder.MODE_INHERITABLETHREADLOCAL);
}
}
still SecurityContext is not passed to the Filter in a pod. (app packaging is WAR) configuration - Spring oauth2-client with JWT authentication (in the header)
Solution
this worked for me:
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws ServletException, IOException {
HttpServletRequest httpServletRequest =
(HttpServletRequest) servletRequest;
Principal userPrincipal = httpServletRequest.getUserPrincipal();
Answered By - Artem Eduardov
Answer Checked By - Mildred Charles (JavaFixing Admin)