Chapter 34: Role-Based Access Control in Kotlin

Restrict routes by user role. In this chapter, you will learn role-based access control in depth with Kotlin code examples, explanations, and best practices.

Overview

This chapter covers role-based access control for Kungfu.js developers using Kotlin. We will start with the basics, move through practical examples, and end with advanced techniques and common pitfalls.

Why This Matters

Understanding role-based access control is essential because it is a core part of building web applications. Every real-world app needs to handle restrict routes by user role. Skipping this chapter would leave a gap in your knowledge that would cause problems later.

Code Example

Here is how authentication works in Kotlin:

use kungfu_core::auth_ext::{require_role, require_any_role};

// Only admins
Kungfu::new()
    .use_middleware(require_role("admin"))
    .handle_get("/admin", |_req, res| res.text("admin panel"))

// Admins or editors
    .use_middleware(require_any_role(vec!["admin".into(), "editor".into()]))
    .handle_get("/content", |_req, res| res.text("content management"))

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 role-based access control in Kotlin. You saw code examples, understood how things work under the hood, and learned about common mistakes to avoid.

What is Next?

In chapter 35, we will cover OAuth2 Integration: Google, GitHub, Discord login.