Kubernetes ingress-nginx sticky session isn't working with spring security

10/30/2019

I have a stateful spring application and I want to deploy it to kubernetes cluster. There will be more than one instance of the application so i need to enable sticy session using ingress-nginx controller. I made the following configuration:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: ingress-nginx
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/ssl-redirect: "false"
    nginx.ingress.kubernetes.io/affinity: "cookie"
    nginx.ingress.kubernetes.io/session-cookie-name: "JSESSIONID"
    nginx.ingress.kubernetes.io/session-cookie-expires: "172800"
    nginx.ingress.kubernetes.io/session-cookie-max-age: "172800"
    nginx.ingress.kubernetes.io/session-cookie-path: /ingress-test
    # UPDATE THIS LINE ABOVE
spec:
  rules:
     - http:
        paths:
          - path: /ingress-test
            backend:
              serviceName: ingress-test
              servicePort: 31080

ingress-nginx redirect subsequent request to correct pod if login is successful. However, it sometimes switches to other pod just after JSESSIONID is changed (JSESSIONID cookie is changed by spring-security afer successful login) and frontend redirects back to login page even user credentials are correct. Is there anyone that tried ingress-nginx with spring-security?

Best Regards

-- savas
kubernetes
spring
spring-security
sticky-session

2 Answers

10/30/2019

The reason spring changes the cookie is to prevent session fixation (more information can be found here: https://www.owasp.org/index.php/Session_fixation). In your case you are using the same cookie for the sticky routing policy that is used by spring for session handling.

I suggest to use a different cookie name - it will be created by nginx and there is no need to use a cookie that is used by the application.

-- Thomas
Source: StackOverflow

10/30/2019

Following change fixed the problem. Without a host definition in rules, ingress-nginx doesn't set session cookie.

There is an open issue: https://github.com/kubernetes/ingress-nginx/issues/3989

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: ingress-nginx
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/ssl-redirect: "false"
    nginx.ingress.kubernetes.io/affinity: "cookie"
    nginx.ingress.kubernetes.io/session-cookie-name: "route"
    nginx.ingress.kubernetes.io/session-cookie-expires: "172800"
    nginx.ingress.kubernetes.io/session-cookie-max-age: "172800"
    nginx.ingress.kubernetes.io/session-cookie-path: /ingress-test
    # UPDATE THIS LINE ABOVE
spec:
  rules:
     - host: www.domainname.com
       http:
        paths:
          - path: /ingress-test
            backend:
              serviceName: ingress-test
              servicePort: 31080
-- savas
Source: StackOverflow