Use OpenID Connect for login and OAuth 2.0 access tokens for API calls, with Spring Security validating tokens on the API. Identity provider Keycloak, Auth0, Okta, Microsoft Entra ID or Spring Authorization Server. Register the React app as a client and the API as a resource (audience) with scopes such as orders.read. Option A — SPA as a public client (Authorization Code flow with PKCE) 1. React (using oidc-client-ts or react-oidc-context, or a provider SDK) redirects to the identity provider with a PKCE code challenge. 2. After login, it exchanges the code for an ID token and an access token (and a refresh token with rotation). 3. API calls include Authorization: Bearer <access token>. Never use the deprecated implicit flow. Avoid storing tokens in localStorage; keep them in memory where possible. Option B — Backend-for-Frontend (recommended for high security) - A Spring Boot BFF (spring-boot-starter-oauth2-client, or Spring Cloud Gateway with TokenRelay) performs the login as a confidential client and stores tokens server-side. - The browser receives only a Secure, HttpOnly, SameSite session cookie; the BFF attaches access tokens when proxying to APIs. - Tokens are never exposed to JavaScript, reducing XSS impact. Add CSRF protection for cookie-based requests. Spring Boot API as a resource server spring.security.oauth2.resourceserver.jwt.issuer-uri=https://idp.example.com/realms/shop @Bean SecurityFilterChain api(HttpSecurity http) throws Exception { return http .authorizeHttpRequests(a -> a .requestMatchers(HttpMethod.GET, "/api/orders/**").hasAuthority("SCOPE_orders.read") .anyRequest().authenticated()) .oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults())) .build(); } Spring Security validates the JWT signature using the issuer's JWKS keys, plus issuer and expiry; add an audience validator to ensure the token was issued for this API. Map roles from custom claims with a JwtAuthenticationConverter. Authorization - Method security (@PreAuthorize("hasRole('ADMIN')")) and resource ownership checks (users access only their own orders). - React route guards only improve user experience; the API enforces all rules. Other essentials - Strict redirect URI allow-lists, strict CORS, short-lived access tokens with refresh token rotation, logout that revokes the refresh token and ends the identity provider session, HTTPS everywhere, and a Content-Security-Policy to reduce XSS risk.
Ravindra Wadile · · 0 likes