<p>I try to port an ASP.NET Core 1 application with Identity to Kubernetes. The login doesn't work and I got different errors like <em><a href="https://stackoverflow.com/a/53870092/9428314">The anti-forgery token could not be decrypted</a></em>. The problem is that I'm using a deployment with three replica sets so that further request were served by different pods that don't know about the anti-forgery token. Using <code>replicas: 3</code> it works.</p>

<p>In the same question I found a <a href="https://kubernetes.github.io/ingress-nginx/examples/affinity/cookie/" rel="nofollow noreferrer">sticky session documentation</a> which seems a solution for my problem. The cookie name <code>.AspNetCore.Identity.Application</code> is from my browser tools. </p>

<pre><code>apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  name: myapp-k8s-test
  annotations:
    nginx.ingress.kubernetes.io/affinity: "cookie"
    nginx.ingress.kubernetes.io/session-cookie-name: ".AspNetCore.Identity.Application"
spec:
  replicas: 3
  template:
    metadata:
      labels:
        app: myapp-k8s
    spec:
      containers:
      - name: myapp-app
        image: myreg/myapp:0.1
        ports:
        - containerPort: 80
        env:
        - name: "ASPNETCORE_ENVIRONMENT"
          value: "Production"
      imagePullSecrets:
      - name: registrypullsecret
</code></pre>

<p>This doesn't work, either with or without leading dot at the cookie name. I also tried adding the following annotations</p>

<pre><code>kubernetes.io/ingress.class: nginx
nginx.ingress.kubernetes.io/session-cookie-hash: sha1
</code></pre>

<p>What is required to allow sticky sessions on Kubernetes with ASP.NET Core?</p>

<p>Found out that I made two logical mistakes: </p>

<ol>
<li>Sticky sessions doesn't work this way</li>
</ol>

<p>I assumed that Kubernetes will look into the cookie and create some mapping of cookie hashes to pods. But instead, another session is generated and append to our http header. <code>nginx.ingress.kubernetes.io/session-cookie-name</code> is only the name of those generated cookie. So per default, it's not required to change them. </p>

<ol start="2">
<li>Scope to the right object</li>
</ol>

<p>The annotations must be present on the ingress, NOT the deployment (stupid c&amp;p mistake)</p>

<pre><code>apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: myapp-k8s-ingress
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/affinity: "cookie"
    nginx.ingress.kubernetes.io/session-cookie-hash: sha1

spec:
  tls:
  - hosts:
    - myapp-k8s.local
  rules:
  - host: myapp-k8s.local
    http:
      paths:
      - path: /
        backend:
          serviceName: myapp-svc
          servicePort: 80
</code></pre>

<p>This works as expected. </p>
