Step 9 — Authentication

JWT auth, role-based access control, all declared in HTML.

How auth works

The What framework uses JWT tokens stored in a cookie. When a user logs in via POST /w-auth/login, the server issues a JWT containing their user_id, email, full_name, and role. Every subsequent request is verified against this token.

JWT Cookie contents
{
  "user_id": 42,
  "email": "[email protected]",
  "full_name": "Jane Smith",
  "role": "admin"
}

Configuring auth in what.toml

[auth]
enabled = true
jwt_secret = "your-secret-key-here"
cookie_name = "w_auth"
expiry_days = 7

User variables in templates

When a user is logged in, these variables are available in all templates:

Variable Value
#user.authenticated# true or empty
#user.email# [email protected]
#user.full_name# Jane Smith
#user.role# admin, editor, user, etc.

Conditional UI based on auth

Show and hide content based on whether the user is logged in or their role.

<if user.authenticated>
  Welcome, #user.full_name#!
  <a href="/dashboard">Dashboard</a>
  <else/>
  <a href="/login">Log in</a>
</if>

<if user.role == admin>
  <a href="/admin">Admin Panel</a>
</if>
Live example (your current auth state)
Not logged in. Auth is not configured in this tutorial project.

Protecting pages with auth directives

Set auth: in the page's <what> block to restrict access. Unauthenticated requests redirect to /login.

<!-- Public page -->
<what>
auth: all
</what>

<!-- Any logged-in user -->
<what>
auth: user
</what>

<!-- Admin or editor only -->
<what>
auth: admin, editor
</what>

You can also set auth: user in application.what to protect an entire directory at once.

Login and logout

<!-- Login form -->
<form method="post" action="/w-auth/login">
  <input name="email" type="email" w-required>
  <input name="password" type="password" w-required>
  <button type="submit">Log in</button>
</form>

<!-- Logout button -->
<form method="post" action="/w-auth/logout">
  <button type="submit">Log out</button>
</form>

Successful login redirects to the redirect form field value, or / by default.

What you learned
  • Auth uses JWT cookies — configure in what.toml under [auth]
  • User variables: #user.authenticated#, #user.email#, #user.full_name#, #user.role#
  • <if user.authenticated> for conditional UI
  • auth: user / auth: admin, editor in <what> blocks protects pages
  • Login: POST /w-auth/login — Logout: POST /w-auth/logout
  • Set auth: in application.what to protect entire directories