October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk9 min

Spring Boot: How to Fix OAuth2 ERR_TOO_MANY_REDIRECTS

A practical guide to diagnosing Spring Boot OAuth2 redirect loops by following Location headers, checking proxy scheme handling, and verifying callback and session behavior.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

ERR_TOO_MANY_REDIRECTS is a browser symptom, not a specific OAuth2 error. In a Spring Boot application, the loop most often comes from incorrect reverse-proxy scheme or host detection, a session cookie that is missing on the callback, or custom security rules that send the browser back to login. Inspect the redirect chain first; its Location headers usually show which layer is repeating the redirect.

Find the redirect that repeats

Open your browser’s developer tools, select the Network panel, enable Preserve log, and reproduce the login. Inspect the status and Location header for each 301, 302, 303, 307, or 308 response. Note the host, scheme, and path at every step, and check whether the session cookie is set and sent again on the application callback.

As an Amazon Associate I earn from qualifying purchases.

A typical Spring Security servlet login should move from a protected page to the authorization endpoint, then to the identity provider, back to the application callback, and finally to the authenticated destination. For example:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
https://app.example.com/private
302 -> https://app.example.com/oauth2/authorization/google
302 -> https://accounts.google.com/...
302 -> https://app.example.com/login/oauth2/code/google
302 -> https://app.example.com/private

If instead the trace alternates between https and http, switches to an internal hostname, or repeatedly returns to /login, investigate that pattern before changing the provider registration. A command-line check can reveal an application-only loop, though it does not reproduce a browser completing an interactive OAuth login:

curl -k -sS -D - -o /dev/null https://app.example.com/login

To limit a redirect-following test:

curl -k -I -L --max-redirs 10 https://app.example.com/

Use -k only for diagnosis when the endpoint has a certificate problem; it skips certificate verification and is not a production fix.

Confirm the authorization and callback URLs

For the default Spring Security servlet OAuth2 login, the authorization initiation path is /oauth2/authorization/{registrationId}, and the callback pattern is /login/oauth2/code/{registrationId}. With a registration named google, the default callback is /login/oauth2/code/google. The default redirect URI template is {baseUrl}/login/oauth2/code/{registrationId}. See the Spring Security OAuth2 Login documentation and its advanced configuration reference.

The provider’s authorized redirect URI must match the URI Spring sends: scheme, hostname, port, context path, callback path, registration ID, and relevant trailing slash. A mismatch often produces an explicit provider error such as redirect_uri_mismatch; that is different from a browser repeatedly following redirects. Do not alter the provider’s URI until you have checked the actual redirect_uri in the authorization request.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Current Spring Security documentation uses the redirect-uri property. Older Spring Security documentation may use redirect-uri-template, so check your dependency version before copying configuration; see the Spring Security 5.2 reference.

Correct proxy and HTTPS handling

A common production mismatch looks like this: the browser visits https://app.example.com, a TLS-terminating proxy forwards to the app over http://app:8080, and Spring builds redirects using the internal HTTP request rather than the public URL. The result can be an HTTPS-to-HTTP loop, an internal host in the OAuth request, or a callback that does not match the provider registration.

For current Spring Boot versions, evaluate this setting when the proxy sends correct forwarded headers:

server:
  forward-headers-strategy: framework

FRAMEWORK uses Spring’s forwarded-header support. NATIVE delegates to the embedded server where supported. Choose the strategy that matches the server and deployment rather than enabling both indiscriminately. Spring Boot documents these options in its web server guidance and the application properties reference.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For Tomcat when TLS terminates at the proxy, also evaluate:

server:
  forward-headers-strategy: framework
  tomcat:
    redirect-context-root: false

This setting is relevant because the forwarded protocol must be honored before redirects are generated. It is not a universal fix for every proxy or container.

A proxy must preserve the external host and scheme and provide a consistent forwarded-header contract. An Nginx configuration might look like this:

location / {
    proxy_pass http://spring-app:8080;

    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_set_header X-Forwarded-Host $host;
    proxy_set_header X-Forwarded-Port $server_port;
}

Treat this as an example, not a drop-in configuration: proxy topology and TLS termination determine the correct values. Trust forwarded headers only from infrastructure you control. Accepting client-supplied forwarded host or scheme values can enable unsafe URL construction or redirects; see Spring Security’s guidance on HTTP security and proxy servers.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

On Kubernetes, verify that the ingress preserves the public host, conveys the external HTTPS scheme, does not rewrite the callback path, and routes callback requests to the intended application. Header behavior varies by controller, version, and configuration. If the public endpoint has a path prefix such as /portal, make sure proxy rewriting, Spring’s context path, and the registered callback URI agree.

Check whether the session survives the provider round trip

The default servlet OAuth2 login flow stores authorization-request state in the HTTP session. The authenticated session is also commonly used after login. If the browser does not return the session cookie on the callback, Spring may treat the request as a fresh unauthenticated visit and start login again.

In the Network panel, inspect the response that starts authorization for a Set-Cookie: JSESSIONID=... header, then inspect the callback request for Cookie: JSESSIONID=.... If the cookie is absent, check its domain and path, whether it has the required Secure attribute, whether the callback uses the same hostname, and whether an intermediary strips or rewrites cookies. Also check for separate cookies created by HTTP and HTTPS versions of the site.

Spring Boot exposes a SameSite setting for the servlet session cookie. Use a value based on the actual browser flow and cookie behavior, not as a blanket OAuth fix:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
server:
  servlet:
    session:
      cookie:
        same-site: lax

Only use SameSite=None when the architecture genuinely requires cross-site cookie use, and pair it with Secure over HTTPS:

server:
  servlet:
    session:
      cookie:
        same-site: none
        secure: true

Modern browsers require Secure for SameSite=None. SameSite cannot fix a wrong host, callback mismatch, missing session store, or proxy misconfiguration. See Spring Boot’s servlet web reference and Spring Boot 3.5 servlet reference.

For multiple replicas, determine whether the callback can reach a different instance from the one that created the session. Session affinity can keep a browser on one node, while shared session storage can make sessions available across nodes; each has operational trade-offs. Neither helps if the browser refuses to send the cookie.

Review security rules and custom login handlers

Check that the authorization initiation endpoint is reachable, the callback is handled by the active Spring Security filter chain, and an error or login page does not immediately trigger another authentication challenge. A minimal servlet configuration to compare against is:

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    http
        .authorizeHttpRequests(auth -> auth
            .requestMatchers("/", "/error", "/oauth2/**", "/login/**").permitAll()
            .anyRequest().authenticated()
        )
        .oauth2Login(Customizer.withDefaults());

    return http.build();
}

This is a diagnostic baseline, not a rule that every application should permit every path under /login/**. Tailor access rules to the app, and verify that the callback still reaches the OAuth2 authentication processing logic rather than being intercepted by another chain or custom rule.

A custom login page configured with .loginPage("/login") should render a page rather than redirect to itself. Its provider link can point to /oauth2/authorization/google. Inspect custom success and failure handlers as well: a failure handler that sends the browser to an endpoint that immediately starts OAuth login can create a repeating cycle. A callback that reaches the application but fails may reflect invalid client credentials, rejected state, a callback mismatch, user-info or ID-token processing failure, access denial, or a custom handler—not necessarily a proxy problem.

Spring Security’s standard login flow is session-backed. A configuration using SessionCreationPolicy.STATELESS is generally incompatible with the default servlet flow unless the application supplies an alternative way to preserve authorization-request state and handle post-login authentication. Browser login, a bearer-token API, an SPA with a backend-for-frontend, and an OAuth2 client calling outbound APIs are different architectures; do not make a browser login stateless just because an API is stateless.

Change the callback path only for a concrete reason

The default callback is usually the simplest option. If you deliberately customize it, configure the Spring Security redirection endpoint and the client registration to match. For example:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
http.oauth2Login(oauth -> oauth
    .redirectionEndpoint(redirection ->
        redirection.baseUri("/login/oauth2/callback/*")
    )
);

The client registration must then use a corresponding template:

Best Value
BookFactory Security Pass Down Log Book, Wire-O, 100 Pages
  • Made in USA - Proudly produced in Ohio by a Veteran-owned business
  • Comprehensive Coverage: This BookFactory log book includes essential fields such as post/shift, time of change, date, weather conditions, and a designated space for detailed notes. This ensures that all relevant information is captured and easily accessible.
  • Sturdy Cover: The trans-lux cover protects the log book from wear and tear, ensuring its longevity and maintaining the integrity of your recorded data.
  • Essential Security Tool: This log book is an indispensable tool for any organization that values security and accountability. It helps to prevent misunderstandings, improve communication, and ensure a smooth transition between shifts.
  • Wire-O with Trans-lux cover, 100 Pages, Dimensions 8.5" x 11" - (Security-Pass-Down) Reorder SKU: LOG-100-7CW-PP(Security-Pass-Down)
.redirectUri("{baseUrl}/login/oauth2/callback/{registrationId}")

Register the resulting public callback URI with the identity provider. Spring Security documents that the client redirect URI must correspond to the customized redirection endpoint in its advanced OAuth2 login reference.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Use the redirect pattern to choose the next check

Observed pattern Likely layer First check
HTTPS and HTTP alternate Proxy or scheme handling Forwarded protocol headers and server.forward-headers-strategy
Public host alternates with an internal host Proxy host forwarding Host, X-Forwarded-Host, and the generated redirect_uri
/login repeats Custom login page or handler Login controller and failure redirect
Root or protected page alternates with /oauth2/authorization/… Authorization rules or saved-request behavior Whether login initiation is reachable and the success destination is protected
Callback returns to /login Authentication failure Security logs, callback matching, and session/state
Each request appears to create a new session Cookie scope or session persistence Cookie attributes, proxy handling, and replica session sharing
Works on one replica but fails on another Distributed session handling Session affinity or shared session storage
Provider reports a redirect URI error Client registration Exact public URI Spring sends versus the provider’s registered URI

Apply a safe diagnostic baseline

  1. Record the versions. Check the Spring Boot and Spring Security versions before copying property names. Current Boot documentation uses server.forward-headers-strategy; older Boot documentation uses server.use-forward-headers. See the Spring Boot 2.7.6 reference and the current properties reference.
  2. Capture the chain. Preserve the browser Network log and write down every redirect destination, including scheme, host, and path.
  3. Compare public and generated URLs. Check the authorization request’s redirect_uri against the provider registration and the public callback URL.
  4. Check session continuity. Confirm that the session cookie set before leaving for the provider is sent on the callback, and verify replica/session behavior if applicable.
  5. Inspect application decisions. In a non-production environment, temporarily enable focused logging:
logging:
  level:
    org.springframework.security.web.FilterChainProxy: DEBUG
    org.springframework.security.oauth2.client: DEBUG

Log wording and internal class details can vary by Spring Security version; use the logs to establish which chain handled the request and whether authentication succeeded, not to match a promised exact message. Avoid exposing client secrets, authorization codes, ID tokens, access tokens, or sensitive user claims. Do not disable HTTPS, CSRF protection, or security rules as a first response to a loop.

Account for older Boot versions and deployment-specific URLs

Older Spring Boot documentation describes server.use-forward-headers; newer Boot lines use server.forward-headers-strategy. Do not set the old and new properties as if they were interchangeable across every release. Confirm the property supported by the Boot version you deploy.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For a single canonical public address, an explicit redirect URI can be appropriate:

spring:
  security:
    oauth2:
      client:
        registration:
          google:
            client-id: ${GOOGLE_CLIENT_ID}
            client-secret: ${GOOGLE_CLIENT_SECRET}
            redirect-uri: "https://app.example.com/login/oauth2/code/google"

For environments where the public base URL is correctly reconstructed from trusted forwarded request information, the template form is useful:

redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"

Spring Security also documents URI template variables such as {baseScheme}, {baseHost}, {basePort}, and {basePath} in its OAuth2 login reference. Dynamic host reconstruction depends on correct proxy headers and safe host handling. If a deployment accepts several hostnames, standardize on one public hostname for login or ensure each generated callback is registered and intentionally supported.

Finally, distinguish servlet applications from WebFlux applications: their request and forwarded-header configuration can differ. If the callback reaches the wrong security chain, verify the application stack and chain matchers before changing OAuth settings. A CDN or ingress that caches redirects or rewrites paths can also make an otherwise correct application appear inconsistent; check the response at both the public edge and the application.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.