spring-projects / spring-security-kerberos

Spring Security Kerberos

Home Page:https://spring.io/projects/spring-security-kerberos

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

SpnegoAuthenticationProcessingFilter does not save the SecurityContext in the Session

JosephThibaultSIB opened this issue · 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);
  }
}

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.

I just opened PR #230, that provides the ability to set a SecurityContextRepository to ensure the SecurityContext is persisted in the session.