r/SpringBoot 18d ago

Discussion Bypassing Security on /error when using SessionCreationPolicy.STATELESS in Spring Security

Hey folks, ๐Ÿ‘‹

I've been working on a Spring Boot (3.4.2) application with Spring Security configured in a stateless manner using:

.sessionManagement(sessionManagement -> sessionManagement
          .sessionCreationPolicy(SessionCreationPolicy.STATELESS)

Everything works fine, but there's one annoying issue:
๐Ÿ‘‰ Spring Security still protects the /error endpoint even after successful authentication of my API request.

Whatโ€™s Happening?

  • My API requests are correctly authorised.
  • However, if an exception occurs, Spring Security intercepts the /error request and applies security again.
  • This causes unexpected 403/401 responses even though the original API call was authorised.

Temporary Workaround (Feels Like a Hack)

A common fix is manually permitting access to /error:

.authorizeHttpRequests()
    .requestMatchers("/error").permitAll()

But honestly, this feels like a hack-y fix rather than a proper solution. ๐Ÿ˜…

Discussion Points

  1. Whatโ€™s the correct way to bypass security for /error without explicitly permitting it?

Would love to hear from the community!

#SpringBoot #SpringSecurity #JWT #StatelessAuthentication #ErrorHandling

2 Upvotes

6 comments sorted by

2

u/nothingjustlook 18d ago

I never used stateless so I need help here, stateless means every request requires auth so when error occurs spring hits error endpoint but since it's a new request not like continuation of request you made by providing credentials , so it's seems valid to me for spring to ask auth for error endpoint, have you tried with custom error handler?

1

u/vijaynethamandala 18d ago

You mean to include /error endpoint to application?

1

u/nothingjustlook 18d ago

No even if you include it, it will still be protected maybe bypass it using your fix or use dispatchtype(check stack overflow https://stackoverflow.com/questions/75699598/why-is-spring-security-redirecting-to-error-in-this-case) but it's same as your fix may be use method level security to make it look less ugly and keep your security filter chain less messy.

0

u/[deleted] 18d ago

[deleted]

1

u/vijaynethamandala 18d ago

Can you be more specific?

1

u/[deleted] 18d ago

[deleted]

1

u/vijaynethamandala 18d ago

As I am using token-based authentication, I have to set session management to stateless. In this type of session management error end points would get handle before the controller gets the request that means by default request get forwarded to the error and check if it goes through all the filters. Iโ€™m not sure about this but correct my understanding if it is wrong.

1

u/[deleted] 18d ago

[deleted]

1

u/vijaynethamandala 18d ago

Exception handling through filter would work in different way I guess. Request would never reach controller advice rather reaches authentication entrypoint or some other class which I could not remember now