配置Spring Security为REST URL返回403,并重定向到其他URL的登录

yan*_*kee 8 spring-security

我的Web应用程序有一堆"普通"资源(html页面等)以及一些REST资源,这些资源是由前面提到的html页面从JavaScript调用的.

如果存在会话超时,则用户将被重定向到登录表单.这对于"普通"资源来说非常好,但对于REST资源则不然.我只需要403响应,以便JavaScript可以接管并要求用户重新进行身份验证.

网上有无数的例子如何配置每一个,但我找不到一个如何组合方法的例子.我的所有API网址都以"/ api /"开头,因此我需要所有这些网址的403以及所有剩余网址的重定向.我该如何设置?

yan*_*kee 6

我花了一些Spring源代码研究来实现这一点.您可以按如下方式设置身份验证入口点:

<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>
Run Code Online (Sandbox Code Playgroud)

然后可以在Sping Security配置中使用它:

<http ... entry-point-ref="authenticationEntryPoint">
Run Code Online (Sandbox Code Playgroud)