spring-security-kerberos icon indicating copy to clipboard operation
spring-security-kerberos copied to clipboard

SpnegoAuthenticationProcessingFilter does not save the SecurityContext in the Session

Open JosephThibaultSIB opened this issue 2 years ago • 2 comments

Hi, Kerberos Authentication is done on each request because SpnegoAuthenticationProcessingFilter does not save the SecurityContext in the Session. Since Spring Security 6, we must explicitly save the SecurityContext after modification as we can see in the following article : https://docs.spring.io/spring-security/reference/6.0/migration/servlet/session-management.html A workaround to fix the problem is to add the following code in a SuccessHandler

public class KerberosAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

  private final SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder.getContextHolderStrategy();

  private final SecurityContextRepository securityContextRepository = new HttpSessionSecurityContextRepository();

  @Override
  public void onAuthenticationSuccess(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) throws IOException, ServletException {
    SecurityContext context = securityContextHolderStrategy.createEmptyContext();
    context.setAuthentication(authentication);
    securityContextHolderStrategy.setContext(context);
    securityContextRepository.saveContext(context, request, response);
  }
}

JosephThibaultSIB avatar Jan 31 '24 10:01 JosephThibaultSIB

A workaround to fix the problem is to add the following code in a SuccessHandler

public class KerberosAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

  private final SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder.getContextHolderStrategy();

  private final SecurityContextRepository securityContextRepository = new HttpSessionSecurityContextRepository();

  @Override
  public void onAuthenticationSuccess(final HttpServletRequest request, final HttpServletResponse response, final Authentication authentication) throws IOException, ServletException {
    SecurityContext context = securityContextHolderStrategy.createEmptyContext();
    context.setAuthentication(authentication);
    securityContextHolderStrategy.setContext(context);
    securityContextRepository.saveContext(context, request, response);
  }
}

I meet the same problem and this workaround works. Thanks for that! Looking forward to the official fix.

kent010341 avatar Feb 26 '24 09:02 kent010341

I just opened PR https://github.com/spring-projects/spring-security-kerberos/pull/230, that provides the ability to set a SecurityContextRepository to ensure the SecurityContext is persisted in the session.

dodgex avatar Jul 11 '24 07:07 dodgex