PTENES
MODULE 3.4

🎫 Tokens and Access Management

A token is the key that opens the doors to your services: an API, a database, a deploy. If it leaks, you’re the one who pays the price. Here, you’ll learn about token types, how to store them safely, rotate them before they become a problem, and follow the best practices that set professionals apart from amateurs.

6
Topics
45
Minutes
Basic
Level
Hands-on
Type
1

Token Types: API Key, JWT, PAT, and OAuth

One token is a secret piece of text that proves who you are to a service. Instead of typing your username and password every time, you present the token and the door opens. There are several types, each for a different situation. Knowing which one to use prevents headaches and keeps everything safer.

YOUR APPLICATION vault / .env Bearer abc123... the token SERVICE / API ✓ 200 OK access granted periodic rotation

🔑 API Key

A simple, fixed key, like sk_live_a1B2c3.... It identifies the application, not a user. Great for services like email delivery, maps, or AI. When to use: simple machine-to-machine integration.

🎫 JWT

"JSON Web Token". A signed token that carries information (who the user is, how long it’s valid) within itself. It has a short expiration period. When to use: login sessions in web and mobile apps.

👤 PAT

"Personal Access Token". A personal key that acts on your behalf (e.g., a GitHub token for pushing). It replaces your password in scripts and tools. When to use: automation on your behalf, such as deploying via CI.

🔗 OAuth

It's not a single token, but a flow. The user clicks "Sign in with Google" and authorizes your app without ever giving you their password. In the end, you receive an access token. When to use: social login and access to third-party data.

🧠 Analogy: Hotel Keys

Think of a large hotel:

  • •API Key = the master service key to the supply room: it opens everything in that area, always the same one.
  • •JWT = the room's key card: it's valid for just a few days, then it stops working.
  • •PAT = the key to your personal locker: it's yours and acts on your behalf.
  • •OAuth = the valet: you hand over the car key for a moment and they park it, without becoming the car's owner.
2

Storing Tokens Securely on the Server

Having the token is only half the job. The other half is where to store. The golden rule: a token never goes in the code. It goes in a separate file, the .env, which only the server reads and which Git ignores.

The file .env

A plain text file in the format CHAVE=valor, one per line:

# Create and edit the file on the server

$ nano .env

# Inside it, your keys:

DATABASE_URL=postgres://user:senha@host/db

API_KEY=sk_live_a1B2c3d4e5

JWT_SECRET=um-segredo-bem-longo-e-aleatorio

Locking the file: chmod 600

By default, other users on the server can read your files. The command chmod 600 says: "only the owner can read and write; nobody else".

# View the current permissions

$ ls -l .env

-rw-r--r-- 1 deploy deploy 180 jun 16 10:00 .env

# Restrict: only the owner can read and write

$ chmod 600 .env

$ ls -l .env

-rw------- 1 deploy deploy 180 jun 16 10:00 .env

👁 What you’ll see on the screen

Read the fine print on the ls -l. The first 10 tell you who can modify the file:

-rw-------   (after chmod 600)

#  rw- = owner can read and write

#  --- = group can’t do anything

#  --- = others can’t do anything

If it still appears -rw-r--r--, anyone on the server can read it. Run chmod.

⚠️ Common Error

Problem: "I pushed my project to GitHub, and the token became public."
Solution: O .env went to the repository because it wasn't in .gitignore. Add the line .env when .gitignore BEFORE the first commit. If it has already leaked, consider the token compromised: revoke it and generate another one (see topic 3). Deleting the file isn’t enough; it remains in the history.

3

Rotation and Expiration: Change Before There’s a Problem

A token that never changes is a time bomb. The longer it lives, the greater the chance it will leak (in a log, a screenshot, or an old backup). Rotate is to generate a new key from time to time and discard the old one. Expiration is for the token to expire on its own after a set period.

🧠 Analogy: Changing the Lock

When you lose a house key, you don’t pray that no one finds it: you change the lock. Rotating a token is the same idea, but done preventively, from time to time, even when you’re not sure it has leaked. That way, if a copy of the old key ever turns up somewhere, it won’t open anything anymore.

The rotation cycle, step by step

1

Generate the new key

In the service dashboard, create a new token. Don’t delete the old one yet.

2

Update the server

Change the value in .env and restart the application.

$ nano .env

# Replace API_KEY with the new value, save

$ systemctl restart minha-app

3

Confirm that it works

Test the app with the new key. Proceed only if everything looks right.

4

Revoke the old key

Now delete the old token in the dashboard. The old key no longer unlocks the door.

⚠️ Common Error

Problem: "I revoked the old token, and the site went down."
Solution: You revoked it before confirming the new key was working. Always follow this order: generate the new one, update, test, and ONLY THEN revoke the old one. Keeping both valid for a short time prevents taking the service down during the switch.

✓ What TO DO

  • ✓Set a schedule (e.g., rotate every 90 days)
  • ✓Immediately revoke any token that has leaked
  • ✓Prefer tokens with automatic expiration

✗ What NOT to do

  • ✗Use the same key for years without rotating it
  • ✗Ignore a leak "because it seems small"
  • ✗Revoke the old one before testing the new one
4

Secrets Managers: The Professional Vault

O .env works well for one server. But when you have several servers, several people on the team, and dozens of secrets, copying files by hand becomes a nightmare. That's where the secrets managers: programs dedicated to securely storing and delivering secrets.

👁 What you’ll see on the screen

Instead of opening a file, you request the secret with a command, and it appears right away (with a record of who requested it):

# Example with Vault

$ vault kv get secret/minha-app

==== Date ====

API_KEY    sk_live_a1B2c3d4e5

# Example with Doppler

$ doppler secrets get API_KEY --plain

sk_live_a1B2c3d4e5

🛡 Vault (HashiCorp)

A robust, open-source vault. It stores secrets, controls who can access each one, and can even generate temporary credentials that expire automatically. More powerful, it requires more configuration.

📦 Doppler

The simplest, most user-friendly service. You centralize secrets in a dashboard, and it injects them into your apps and environments. A great starting point for small teams.

🧠 Analogy: The Bank Vault

Keeping money under the mattress (the .env (left loose) works up to a point. A secrets manager is the bank vault for your secrets: one place with a reinforced door that records every time someone opens it and can even have keys that only work for a day. You don’t store the actual secret on your machine; you ask the vault for it when you need it.

💡 Tip: Start simple

For a personal project on a single VPS, the .env with chmod 600 is already very good. Only adopt a secrets manager when the need arises: many environments, many people, or too many secrets to manage by hand. The right tool for the right size.

5

Auditing: Who Used What, and When

There’s no point locking everything down if you can’t see what happened. Access auditing is to keep a record (log) of every use: which token, which action, from where, and at what time. When something goes wrong, these logs are your security camera.

Reading an Access Log

Each line tells a story: who, when, what, and the result.

# View the latest recorded accesses

$ tail -n 5 /var/log/minha-app/access.log

10:01 token=deploy  acao=push    ip=200.1.1.5  ok

10:04 token=backup  acao=read    ip=200.1.1.5  ok

10:09 token=deploy  acao=delete  ip=45.9.9.9    ok

10:12 token=deploy  acao=delete  ip=45.9.9.9    FALHA

Notice on line 3: the token deploy deleted something from a strange IP (45.9.9.9). Warning sign.

👁 What you’ll see on the screen

To investigate a specific token, filter the log. The grep shows only the lines that matter:

$ grep "token=deploy" access.log

10:01 token=deploy acao=push   ip=200.1.1.5 ok

10:09 token=deploy acao=delete ip=45.9.9.9  ok

# Filter only the failures

$ grep "FALHA" access.log

10:12 token=deploy acao=delete ip=45.9.9.9  FALHA

🧠 Analogy: The Building’s Guest Book

A well-maintained building has a doorman and a logbook: each visitor's name and arrival and departure times. If something goes missing, you check the book and find out who came by. An access log is this guestbook for your tokens. Without it, you only find out you've been robbed, never by whom.

💡 Tip: Never log the secret itself

In the log, note the name of the token (e.g., token=deploy), never the full value. If you write the entire key in the log, the security record itself becomes a leak. Logs are often read by many people.

6

Best Practices: Least Privilege and One Token per Service

Bringing it all together, two rules do most of the heavy lifting: least privilege (each token can only do what it needs to) and one token per service (never share the same key across different things). Follow this and a leak becomes a scratch, not a catastrophe.

🧠 Analogy: The Caretaker’s Key Ring

Imagine a building where a single key opens EVERY door: apartments, the vault, the garage. If it falls into the street, it’s over. A well-managed building gives each person only the key to THEIR door. Lose one? Change only that lock. Tokens work the same way: one per service, each with the minimum permissions.

✓ What TO DO

  • ✓One token for each service (deploy, backup, monitor)
  • ✓Give only the necessary permission (read access if it doesn’t need to write)
  • ✓Give the token a clear name (token-backup-diario)
  • ✓Immediately revoke tokens belonging to anyone who left the team

✗ What NOT to do

  • ✗One “full admin” key used for everything
  • ✗Send a token carelessly over WhatsApp or email
  • ✗Leave former employees’ tokens active
  • ✗Pasting the token directly into the code "just to test quickly"

Example: separating by service in the .env

# Each service gets its own key with its own name

DEPLOY_TOKEN=ghp_xxxxx    # only pushes, nothing else

BACKUP_TOKEN=bk_yyyyy     # read-only database access

EMAIL_API_KEY=re_zzzzz    # only sends email

# If EMAIL_API_KEY leaks, the deploy and backup remain secure

🏆 You’ve reached the end of Track 3

You hired a VPS provider, connected over SSH, closed the ports with a firewall, and now know how to manage your services’ keys. You have your own secure server under your control. In the next track, you’ll run your applications on it in an organized way, with Docker and automation.

📚 Module Summary

✓
API Key, JWT, PAT, and OAuth - each token type for a different situation
✓
.env + chmod 600 - stored outside the code and readable only by the owner
✓
Rotation and expiration - rotate before there's a problem; generate, test, then revoke
✓
Secrets managers - Vault and Doppler centralize secrets as the team grows
✓
Auditing, least privilege, and one token per service - see who used it and limit the damage

Next Track:

Track 4 - Docker & Automation (package and run your applications on the server in an organized way)