Configure Spring Security to return 403 for REST URLs and redirect to login for other URLs

My web application has a bunch of "normal" resources (html pages, etc.), as well as some REST resources that are called from JavaScript on the previously mentioned html pages.

If there is a session timeout, the user is redirected to the login form. This is great for "normal" resources, but not for REST resources. I just need a 403 answer so that JavaScript can take over and ask the user to re-authenticate.

There are many examples on the Internet for customizing each of them, but I cannot find an example of how to combine the methods. All my API URLs start with "/ api /", so I will need 403 for all of these URLs and a redirect for all other URLs. How to set it up?

+7
spring security
source share
2 answers

It took me a bit to study the Spring source code to get this to work. You can configure the entry point for authentication 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"> 
+6
source share

I think that you should only have two different objects <http pattern="{...}" ...> because, well, you solved the redirect problem, but what about csrf protection? And other problems that I can’t remember.

0
source share

All Articles