0%
Securing REST APIs

REST API

Statelessness, the right error codes, and two protections that are often misunderstood.

15-20 min

Securing REST APIs

Take the configuration of a classic web application, point a JavaScript client at it, and watch what happens: instead of a clean 401, your fetch call receives a 302 redirect to an HTML login page. The client, which was expecting JSON, tries to parse HTML and fails with an incomprehensible message. Nothing is actually broken — Spring Security is doing exactly what it was asked to do, which is to behave as if a browser were following a login flow.

That is the first adjustment to make: an API doesn't redirect, it responds with a status code. The second concerns state. A session-based application stores identity on the server and retrieves it through a cookie; a stateless API requires every request to carry its own proof of identity. Both models work, but they don't have the same vulnerabilities, and the protections suited to one don't suit the other.

This is where the two most widespread mistakes in the field occur. The first is copying csrf.disable() without asking what made that protection necessary — and then disabling it on the parts of the application that use cookies as well. The second is treating CORS as a security mechanism when it isn't one, and opening up access while believing you are controlling it.

Comments

Comments are powered by GitHub Discussions

Sign in with GitHub to join the discussion

Link copied!