Jason Nethercott
Jason Nethercott

Reputation: 393

Spring Security with Okta & custom redirect == Too Many Redirects

When configuring Spring security with a custom redirect URL that uses the basic URI template variables as documented here: https://docs.spring.io/spring-security/site/docs/5.2.12.RELEASE/reference/html/oauth2.html#oauth2Client-auth-code-redirect-uri

The application gets into a loop of too many redirects.

This configuration works: spring.security.oauth2.client.registration.okta.redirect-uri={baseUrl}/login/oauth2/code/{registrationId}

This does not: spring.security.oauth2.client.registration.okta.redirect-uri={baseScheme}://{baseHost}{basePort}{basePath}/login/oauth2/code/{registrationId}

Due to certificates and load balancers and all that, we need to fool spring into redirecting to an https vs the http where it's running. So the baseScheme we need to modify.

Using the base URL, from the browser we see the following cycle:

Using the redirect-url with the baseScheme the cycle is:

What setting might we me missing? Why is Spring going to /oauth2/authorization/okta instead of the original page they called to begin with?

NOTE: a clarification in the redirect back to the app from Okta: Both settings are the exact same redirect URL: .../login/oauth2/code/okta?code=...

My conclusion is: setting the redirect URL is calling Okta properly, but effecting how the application responds to that redirected call.

When debugging is on, here is a working call stack:

And when it's not working:

Upvotes: 0

Views: 1758

Answers (1)

Brian Demers
Brian Demers

Reputation: 2080

There are a couple of questions in this one.

First, you shouldn't need to "fool" Spring into knowing if your app is https or HTTP. I'm guessing you are running behind a reverse-proxy, just make sure the correct X-Forwarded-* headers are set:

https://docs.spring.io/spring-boot/docs/current/reference/html/howto.html#howto.security.enable-https

For the "too many redirects" issue, this is usually a configuration error on the application side (I'm guessing an invalid client-id, client-secret, or issuer.

What often happens is your application redirects to the IdP (Okta) and the IdP authenticates the user, then redirects back to your application.

Your application then makes a backchannel request back to the IdP to validate the user's auth (by exchanging a code). If this exchange fails, you get redirected back to the IdP, but the user is already logged in (SSO), so it sends you back to your application (and round and round you go).

The default logging for Spring Security is a bit sparse (intentionally), but it makes catching things like this difficult, bump the log level: logging.level.com.springframework.security=DEBUG, and you should start seeing exceptions in your log file.

Upvotes: 0

Related Questions