My web application has a bunch "normal" resources (html pages etc) and also some REST resources which are called from JavaScript by the previously mentioned html pages.
If there is a session timeout the user gets redirected to the login form. That's great for the "normal" resources, but not for the REST resources. I'll just need a 403 response there so that the JavaScript can take over and ask the user to reauthenticate.
There are countless examples on the web how to configure each of those, but I could not find an example on how to combine the methods. All my API URLs start with "/api/", so I'll need the 403 for all those URLs and the redirect for all the remaining URLs. How do I set this up?
By default, Spring Security will redirect after login to the secured ressource you tried to access. If you wish to always redirect to a specific URL, you can force that through the HttpSecurity configuration object. Assuming you are using a recent version of Spring Boot, you should be able to use JavaConfig.
Use this: response. setStatus(403) . Save this answer.
The most common ways to implement redirection logic after login are: using HTTP Referer header. saving the original request in the session. appending original URL to the redirected login URL.
It took me a little bit of Spring source code study to get this to work. You can set up an authentication entry point as follows:
<bean id="authenticationEntryPoint" class="org.springframework.security.web.authentication.DelegatingAuthenticationEntryPoint">
<!-- this is the configuration for /api/ URLs -->
<constructor-arg>
<map>
<entry>
<key>
<bean class="org.springframework.security.web.util.matcher.RegexRequestMatcher">
<constructor-arg value="^/api/.*" /><!-- match URLs starting with "/api/" -->
<constructor-arg><null /></constructor-arg><!-- no matter what the HTTP method is -->
</bean>
</key>
<!-- if the key above has matched, send 403 response -->
<bean class="org.springframework.security.web.authentication.Http403ForbiddenEntryPoint" />
</entry>
</map>
</constructor-arg>
<!-- and in the default case just redirect to login form -->
<property name="defaultEntryPoint">
<bean class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint">
<constructor-arg value="/spring_security_login" />
</bean>
</property>
</bean>
This can then be used in the Sping Security configuration:
<http ... entry-point-ref="authenticationEntryPoint">
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With