spring-projects / spring-security-kerberos

Spring Security Kerberos
https://spring.io/projects/spring-security-kerberos
182 stars 226 forks source link

SpnegoAuthenticationProcessingFilter does not save the SecurityContext in the Session #185

Open JosephThibaultSIB opened 8 months ago

JosephThibaultSIB commented 8 months ago

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);
  }
}
kent010341 commented 7 months ago

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.

dodgex commented 3 months ago

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.