---
title: "Problems Encountered When Implementing JWT Authentication"
description: "Notes on issues encountered while introducing JWT authentication into a backend system, covering token storage options, cross-window race conditions, forced logout design, and Redis integration strategy."
canonical_url: "https://blog.markkulab.net/en/post/jwt"
author: "Mark Ku"
author_url: "https://blog.markkulab.net/en/author/mark-ku"
site: "Mark Ku's Tech Notes"
date_published: "2020-07-24 15:01:35 +0300"
category: "Backend"
tags: ["jwt", "authentication", "security", "redis", "backend", "csharp"]
language: "en"
license: "CC BY 4.0"
license_url: "https://creativecommons.org/licenses/by/4.0/"
attribution: "when reusing or quoting, credit the author and link back to the original"
---

# Problems Encountered When Implementing JWT Authentication

## Problems Encountered When Implementing JWT Authentication

## Understanding JWT Tokens

JWT was originally designed to enable secure data exchange across organizational boundaries. Because JWT alone cannot guarantee full security, JWE was introduced as an extension. However, the JWE spec defines many attributes and naming conventions that most projects don't need — I think it's fine to borrow the spirit of the approach without following the spec to the letter.

## Goals

1. Mobile app can share the same authentication flow and API as the web, without maintaining two separate systems.
2. Stateless APIs make it easier to scale servers horizontally — each additional server contributes proportionally to overall throughput.
3. Resolves Same-Site Cookie issues (only relevant on the product side, not the platform side).

## Risks

1. Security is fully controlled by the developer.

## Existing System Dependencies on Session

1. Login state
2. Failed login attempt count
3. IP blocking
4. CAPTCHA

## Existing System Dependencies on Cookie

1. Sticky cookie
2. Data cookie
3. SignalR uses .NET Forms Authentication (cookie-based) — switch to passing the JWT token on connect instead

## JWT Validation Mechanism

To prevent token forgery, the token is written to Redis upon login. Every request must be validated against Redis.

## Where to Store the JWT Token

| Approach | Issues |
| -------- | ------ |
| LocalStorage | XSS vulnerability; doesn't work in mobile private/incognito mode; not supported on older mobile browsers |
| LocalStorage → SessionStorage | LocalStorage has compatibility issues |
| redux-state-sync | Requires EA tech review process — deferred for now |
| **In-Memory** (chosen) | Cross-window state sync is more complex to implement, but has the best compatibility |

Note: Both cookies and LocalStorage create physical files on the client side. Modern browsers encrypt these files, but they can potentially be cracked. SessionStorage is more secure than LocalStorage. Keeping the token in memory (no persistence to disk) is the safest option.

## JWT Token Length

The existing online user count is calculated from the `SessionId` column in the login table, which currently has a maximum length of 100 characters. Standard JWTs are typically longer than 100 characters, so database columns need to be adjusted accordingly.

## Cross-Window Race Condition on Token Refresh

The desktop web app has a "window.open" feature for viewing account history. From Angular's perspective, this spawns an independent app instance. Both the parent window and the child window can trigger token refresh simultaneously, causing a race condition.

My approach: child windows never refresh the token themselves. Instead, they use `postMessage` to notify the parent window to refresh. Subsequent requests are queued in the child window until the parent completes the refresh and signals back to unlock the queue. If the wait exceeds a timeout threshold, the queue is released via RxJS timeout.

## Forced Logout (Kick) Logic

The JWT spec doesn't define forced logout behavior — all kick logic must be implemented manually:

1. Idle timeout (no trades placed)
2. Token expiry
3. Double login (duplicate session)
4. Manual logout
5. Session not properly closed
6. Maintenance kick (from the BO site)

The kick mechanism works by clearing the token in Redis, effectively invalidating it. Log the kick reason for easier debugging later.

## Making JWT More Secure

1. The site must use HTTPS.
2. Shorten the access token lifetime.
3. Bind the access token to a browser fingerprint (Device ID): https://fingerprintjs.com/?fbclid=IwAR1I0nRPyiJJUHosyXa80GwJi45-4tHjxV5uZPnTBks-XT3Kp3-tyi1ln1M
4. Disable DevTools access (F12) — leave a back door for yourself.
5. Log member login history.
6. Bind to IP — though clients may switch networks and mobile IPs can change frequently, this could still be a valid policy as long as the business team accepts that IP changes require re-login. Show the logout reason when it happens.

## Coexisting Session/Cookie Fallback

After going live, if a critical issue arises that takes a long time to fix, it's helpful to be able to quickly roll back to the old mechanism. A coexistence mode is retained where a config flag determines whether Autofac injects JWT or Session logic:

```
   if (IsJWTAuthentication)
   {
        builder.RegisterType<JWTSessionData>().As<ISessionData>();
        builder.RegisterType<JWTAuthenticationBLL>().As<IAuthenticationBLL>();
   }
   else
   {
        builder.RegisterType<SessionData>().As<ISessionData>();
        builder.RegisterType<AuthenticationBLL>().As<IAuthenticationBLL>();
   }
```

## Rough Scope of Work

1. Eliminate Session dependencies
2. Eliminate Cookie dependencies
3. Implement JWT token issuance
4. Implement JWT login/authentication
5. Implement forced logout (kick) functionality
6. Implement token refresh
7. Swap out Session/Cookie mechanism in API layer

---

## Addendum

### Is HTTPS Always Secure?

Not necessarily. The following scenarios can make HTTPS insecure:

1. Using outdated encryption algorithms
2. Bugs in the cryptographic library implementation
3. The Certificate Authority (CA) is compromised
4. Private key leakage
5. Government-level interception (e.g., FBI)

### Side Effects of Binding JWT to IP

Client IPs can change when users switch networks, and mobile IPs are particularly volatile. Binding a token to an IP may not be appropriate for all use cases. That said, it can be a valid policy — as long as the business team agrees that any IP change triggers a forced logout with a reason shown to the user.

## Additional Findings

1. Redux DevTools was not disabled in the production build.

---

## About this article and its author

Originally published on [Mark Ku's Tech Notes](https://blog.markkulab.net/en/post/jwt)

License: [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) — when reusing or quoting, credit the author and link back to the original

### About the author

**[Mark Ku](https://blog.markkulab.net/en/author/mark-ku)** — Software Solution Provider

- 10+ years senior software engineer, now an AI Builder
- Focused on large-platform architecture — North-American e-commerce, AI SaaS subscription billing
- Combining AI Agents and automation to build evolvable product foundations

### Free tools built by the author

All of these are free to use:

- [Free PDF Sign Tool](https://blog.markkulab.net/en/tools/pdf-sign): Online PDF sign tool — draw, type, or upload a signature, then drag, resize, and download. Everything runs in your browser; nothing is uploaded.
- [VS Code Refactory](https://blog.markkulab.net/en/tools/refactory): Refactory is a VS Code refactoring extension: 34 actions plus a 37-rule code-smell inspection layer with a Code Health dashboard, across 18 languages, backed by 534 tests. It learns your repo's conventions: where interfaces live, where DI is registered, whether 'use client' belongs. It ranks files by git churn × complexity so you know what to fix first, and hands any smell to the Claude Code already on your machine. Free to use, and your source never leaves your computer.
- [DB-Kit Database Manager](https://blog.markkulab.net/en/tools/db-kit): DB-Kit is a lightweight, cross-platform database manager built with Tauri + Rust + React. Manage MySQL, MariaDB, PostgreSQL, SQL Server, Oracle, SQLite, MongoDB, Redis, Kafka, Elasticsearch and RabbitMQ from one consistent interface: passwords encrypted in the OS keychain, SSH tunnels, full CRUD, a visual query builder, stacked multi-statement result sets, cross-connection data transfer and compare/sync, Excel / CSV import & export, visualized execution plans, ER diagrams, scheduled backups, SQL stress testing with p50–p99 latency percentiles, a 15-rule SQL review engine, Kafka message browsing with monitoring & alerts, a bilingual UI (Traditional Chinese / English), a built-in AI assistant (natural-language SQL, AI review and tuning advice) and the dbk CLI. Free and open source (MIT), with installers for Windows, macOS and Linux.
- [VS Code Super Mermaid](https://blog.markkulab.net/en/tools/super-mermaid): Super Mermaid is a VS Code extension for beautiful Mermaid diagrams out of the box: auto-colored live preview, mouse pan & zoom, high-res PNG / SVG export, 21 templates and multiple themes. Free and open source (MIT).
- [React Super Mermaid](https://blog.markkulab.net/en/tools/react-super-mermaid): react-super-mermaid is an open-source React component library: render beautiful Mermaid diagrams with a single <MermaidViewer>, with built-in colorful / sketch themes, pan & zoom, in-diagram search, and high-res SVG / PNG export. Lightweight, SSR-safe, fully typed. Free and open source (MIT).
- [Jira / Confluence Super Mermaid](https://blog.markkulab.net/en/tools/jira-super-mermaid): An Atlassian Forge app: write Mermaid syntax directly inside a Jira issue or a Confluence page and get flowcharts, sequence diagrams, state machines and Gantt charts. 11 diagram types, SVG / PNG export, light and dark themes, full CJK support. Runs on Atlassian: your diagrams live in your own site and the app calls no third-party service. Free, coming soon to the Atlassian Marketplace.
- [Mermaid Live Preview](https://blog.markkulab.net/en/tools/mermaid-preview): Write Mermaid in your browser, see it render instantly, and share the whole diagram as a single link. No sign-up, nothing uploaded to a server, and mermaid.live share links work as-is.
- [React Intl Phone Number](https://blog.markkulab.net/en/tools/react-intl-phone-number): react-intl-phone-number is an open-source React component: framework-agnostic and antd-free, with E.164 in/out, a searchable flag / country-code dropdown, configurable validation levels (strict / mobile-strict / loose), themeable CSS, and i18n — phone logic powered by google-libphonenumber. Lightweight and fully typed. Free and open source (MIT).
- [Uptime Kuma Cluster](https://blog.markkulab.net/en/tools/uptime-kuma-cluster): Turn single-node Uptime Kuma into a highly available cluster: OpenResty + Lua smart load balancing, shared MariaDB state, health checks and automatic failover, plus cluster-management REST APIs. One Docker Compose command to start. Free and open source (MIT).
- [Special Education](https://blog.markkulab.net/en/education): Learning materials crafted for special education students

### Daily podcasts

- [Mark's Tech Insights — Daily AI News](https://blog.markkulab.net/en/category/tech-news): Daily curated AI and tech trends. Catch the latest developments via audio summaries — covering AI applications, software architecture, DevOps, and engineering practice. — RSS: https://blog.markkulab.net/feed.xml
- [AI股市蝦聊](https://blog.markkulab.net/en/category/ai-stock-chat): Every trading day, an AI-analyzed take on the Taiwan stock market, delivered as a two-host conversation covering the session and the next-day outlook. — RSS: https://blog.markkulab.net/ai-stock-chat/feed.xml
- [開源好物週報](https://blog.markkulab.net/en/category/open-source-weekly): A weekly two-host pick of free open-source tools surfaced from real Hacker News, GitHub, and Reddit buzz — what pain they solve and the fastest way to get started. — RSS: https://blog.markkulab.net/open-source-weekly/feed.xml

### Newsletter

[Subscribe to the newsletter](https://blog.markkulab.net/en/subscribe) — Be the first to know about new posts. No spam, unsubscribe anytime.
