Spring Security 3 - always return error 302
I believe Spring is redirecting you to /home
because you didn't actually authenticated a User through the login process.
- You access your web-app through
http://mylocal:8080/moon
returning the home.jsp view - You click the SignIn button, submitting your login form
since no form login is explicitly declared, Spring Security will display the username and password prompt box for the end-user to enter its credentials - These credentials are then POSTed to the login processing URL (
/acct/signin
) for which you happen to have a mapping with thesignin
method in theAccountController
- Such controller fails to authenticate a User the Spring way, but still redirect the request to
/demo
by returning a String - The
/demo
path is protected (.anyRequest().authenticated()
) to any unauthenticated user, since the current user is indeed unauthenticated, Spring Security will automatically redirect the request to the login page - You end up on
/home
(.loginPage("/home")
)
Using a InMemoryUserDetailsManagerConfigurer (see inMemoryAuthentication javadoc), you can only successfully login through the configured credentials. If you want a fully-fledged Authentication system, you must provide an UserDetailsService implementation to your Spring Security configuration (through the userDetailsService method).
EDIT : Following the conversation with chialin.lin, it seems the missing configuration was a defaultSuccessfulUrl for Spring Security to know where to redirect the user once authenticated.
For me I came from a little different use-case but 'suddenly' had the same problem before it perfectly worked.
My Setup Spring with a ExtJs frontend where I now build in a rest interface.
It all worked super nice and then suddenly I started having http status 302 responses (WTH?)
Since I implemented by code by following this example: https://octoperf.com/blog/2018/03/08/securing-rest-api-spring-security/
there is a declaration of a SimpleUrlAuthenticationSuccessHandler.
See 4.4 SecurityConfig where the TokenAuthenticationFilter is constructed with a class NoRedirectStrategy; see 4.1 Redirect Strategy
In turn not having this NoRedirectStrategy set up in my extension of the AbstractAuthenticationProcessingFilter it would show me http 302 responses.
To avoid having to create a new trivial SuccessHandler
, override the successfulAuthentication
method in your filter and just call the chain.doFilter()
method after having set the Authentication
object in the security context.