Authentication, Authorization, Sessions and Security
Build secure authentication architecture, understand sessions and tokens, protect routes, enforce authorization, and avoid common security mistakes.
JWT-Based Authentication
A JSON Web Token can carry signed claims that allow a server to verify information without consulting session state for every request. However, JWTs are not automatically encrypted; signing and encryption solve different problems.
JWT-based systems require careful decisions around expiration, refresh tokens, revocation, audience, issuer, and key management.
For browser applications, storing sensitive long-lived tokens in JavaScript-accessible storage can increase the impact of XSS. Cookie-based approaches are often preferable depending on the architecture.
- A signed JWT provides integrity, not necessarily confidentiality.
- Short expiration and careful refresh-token design are important.
- Token storage strategy is a major security decision.
Protecting Server Actions and Route Handlers
A protected page does not automatically protect every backend operation associated with it. A user might directly invoke a Route Handler or Server Action.
Every sensitive operation should establish the authenticated user and verify authorization for the target resource.
For example, deleteInvoice(invoiceId) must verify that the current user owns the invoice or has the appropriate role before deleting it.
export async function deleteInvoice(invoiceId: string) {
const user = await requireUser();
const invoice = await getInvoice(invoiceId);
if (!invoice || invoice.ownerId !== user.id) {
throw new Error('Not authorized');
}
await removeInvoice(invoiceId);
}- Protect mutations independently.
- Check ownership or role permissions.
- Never assume route-level protection covers every backend operation.
CSRF, XSS and Input Security
Cross-Site Request Forgery abuses a user's authenticated browser context to perform unwanted actions. Cross-Site Scripting attempts to execute attacker-controlled JavaScript in a user's browser.
React escapes normal text output, which provides an important baseline against XSS, but unsafe HTML rendering, third-party scripts, insecure DOM APIs, and poorly sanitized content can reintroduce risks.
Authentication architecture should consider CSRF protection, especially when authentication relies on cookies and cross-origin requests are involved.
Authentication libraries do not eliminate application-level authorization, input validation, CSRF considerations, secret management, or secure coding practices.
- Treat all external input as untrusted.
- Avoid unsafe HTML injection unless content is properly sanitized.
- Consider CSRF explicitly when using cookie-based authentication.