PDStat
PDStat

Reputation: 5835

Spring Boot/Security - Custom 404 page

I have created a custom 404 error page in my Spring Boot app, I also use Spring Security and I have an authentication entry point with a number of authorised URL's (error page included in that list).

What I'm finding is that if I enter a URL that doesn't exist the authentication entry point intercepts the request as it isn't an authorised URL and I end up back at my login page instead of the custom 404 error page. Any ideas?

Basic example of what I have in the security config

http
    .csrf().disable()
        .authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login"))
    .and()
        .authorizeRequests().antMatchers("/login", "/error-404")

Upvotes: 0

Views: 755

Answers (1)

Filip Hanik VMware
Filip Hanik VMware

Reputation: 1622

Here is what Spring Security will do when you invoke /invalid-url

If /invalid-url is secure (default)

  1. Store the request (/invalid-url -> session)
  2. Invoke authentication entry point
  3. Redirect to /login
  4. User will authenticate
  5. Upon successful authentication, redirect to stored request /invalid-url
  6. Page not found - redirect to error handler

If /invalid-url is not secure

  1. Page not found - redirect to error handler

So basically, you'd need to declare all your non secure URLs if you want the second flow, directly go to 404 page

.mvcMatchers("/login", "/error-404/**", "/invalid-url/**").permitAll()

Obviously doing this:

.anyRequests().permitAll()

as the last statement will solve your use case, it is also dangerous. You have then explicitly map out any endpoint that must be secured. And if you forget one, that endpoint will be left exposed.

Upvotes: 1

Related Questions