Chapter 33: Session Authentication in C++

Cookie-based sessions with server store. In this chapter, you will learn session authentication in depth with C++ code examples, explanations, and best practices.

Overview

This chapter covers session authentication for Kungfu.js developers using C++. We will start with the basics, move through practical examples, and end with advanced techniques and common pitfalls.

Why This Matters

Understanding session authentication is essential because it is a core part of building web applications. Every real-world app needs to handle cookie-based sessions with server store. Skipping this chapter would leave a gap in your knowledge that would cause problems later.

Code Example

Here is how authentication works in C++:

use kungfu_core::auth_ext::{SessionStore, session_auth};
use std::sync::Arc;

let store = Arc::new(SessionStore::new());

// Create a session
let session_id = store.create("user123", json!({"role":"admin"}), 3600);

// Protect routes
Kungfu::new()
    .use_middleware(session_auth(store.clone()))
    .handle_get("/dashboard", |_req, res| res.text("welcome"))

Security Best Practices

Never store passwords in plain text. Kungfu.js uses Argon2id, which is the winner of the Password Hashing Competition. It is designed to be resistant to GPU and ASIC attacks.

JWT tokens should have an expiration time. A good default is 1 hour for access tokens and 7 days for refresh tokens. Kungfu.js validates the expiration automatically.

Common Mistakes

  • Not reading the documentation: Always check the API reference when something does not work as expected.
  • Skipping security: Never disable the default middleware unless you have a very good reason. Security is not optional.
  • Not testing: Write tests for your handlers. Kungfu.js makes this easy with the built-in test utilities.

Summary

In this chapter, you learned about session authentication in C++. You saw code examples, understood how things work under the hood, and learned about common mistakes to avoid.

What is Next?

In chapter 34, we will cover Role-Based Access Control: Restrict routes by user role.