Security
Authentication
Find out who is calling: passwords, tokens, API keys.
Authentication answers "who are you?". (Its partner, authorization, answers "what may you do?".) A client proves its identity, the server remembers who it is for the rest of the request, and your code can use it.
The idea: sign in once, then carry a token
Sending the password with every request would be unsafe. Instead the client signs in once and receives a token it then sends with each request. Kest supports tokens called JWT (JSON Web Tokens): a small signed piece of text that says "this is user 42, with roles USER, valid until 14:00". Only your server can create a valid one (it signs with a secret), so it can trust the token without looking anything up.
Step 1: configure tokens
Kest.run<AppModule> {
import(JwtModule.register {
secret = System.getenv("JWT_SECRET") // long and random (32+ bytes); never in the source code
expiresIn = Duration.ofHours(1) // tokens stop working after an hour
issuer = "shop-api" // optional: checked when verifying
})
}JwtService signs and verifies HS256, HS384, HS512 (one shared secret) and RS256 (a private key signs, a public key verifies: set privateKeyPem and publicKeyPem, handy when other services only verify).
Step 2: a login endpoint
@Injectable
class AuthService(private val jwt: JwtService, private val users: UserService, private val hasher: PasswordHasher) {
fun login(email: String, password: String): String {
val user = users.byEmail(email)?.takeIf { hasher.verify(password, it.passwordHash) }
?: throw UnauthorizedException("Bad credentials") // the SAME message for "no such user" and "wrong password"
return jwt.sign(mapOf("sub" to user.id, "roles" to user.roles)) // what goes in the token: an id and the roles
}
}
@Controller("/auth") class AuthController(private val auth: AuthService) {
@Public @Post("/login") fun login(@Body body: LoginDto) = mapOf("token" to auth.login(body.email, body.password))
}Store hashes, never passwords (Encryption and hashing). Give the same error for an unknown email and a wrong password, so attackers cannot discover which emails are registered, and rate-limit the login route.
Step 3: protect routes
@Controller("/orders") @Authenticated class OrdersController {
@Get fun mine(user: JwtPrincipal): List<Order> = orders.forUser(user.id) // the verified caller, as a parameter
@Public @Get("/count") fun count() = orders.count() // one method left open
}@Authenticated needs a signed-in caller and works on a class or on single methods, with no global guard (Authorization). A missing, expired or tampered token is a 401. The caller is found by the Authenticator providers: JwtModule provides one for Bearer tokens; add others for API keys or Basic auth:
import(AuthenticationModule.forRoot(
ApiKeyStrategy("x-api-key", mapOf("secret-key-1" to SimplePrincipal("billing-service", setOf("SERVICE")))),
BasicStrategy { user, pass -> if (users.check(user, pass)) SimplePrincipal(user, setOf("USER")) else null },
))Or protect everything at once: app.http(adapter) { useGuards(JwtAuthGuard::class) } (then mark open routes @Public).
What goes in a token, and what does not
- Put: the user id (
sub), roles, an expiry. Keep it small: it is sent with every request. - Do not put secrets or personal data. A JWT is signed, not encrypted: anyone holding it can read its contents.
- Expiry matters. A stolen token works until it expires, so keep access tokens short (minutes to an hour). For "stay signed in for a month", issue a longer-lived refresh token (stored server-side so you can revoke it) that is exchanged for new short access tokens.
- You cannot cancel a JWT before it expires without a lookup. If you need instant logout or a "ban", keep a small revocation list or use sessions.
Tokens or sessions?
| JWT in a header | Server session + cookie | |
|---|---|---|
| state | in the token (stateless) | stored on the server (Session) |
| works across services | yes | needs a shared store |
| instant logout | needs extra work | easy |
| browser app | store carefully (see Next.js) | cookie, with CSRF protection |
| mobile apps, other servers | natural | awkward |
Sign in with another provider
Google, GitHub, Microsoft, Facebook, X, Apple and any OpenID Connect provider: see Social login.
Checklist
- HTTPS everywhere (tokens are bearer secrets: anyone who sees one can use it).
- A strong, secret signing key from your secrets store; rotate it on a schedule.
- Short expiry, rate-limited login, hashed passwords, identical failure messages.
- Test the refusals: no token, wrong token, expired token, wrong role.