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

Posted

技术标签:

【中文标题】配置 Spring Security 为 REST URL 返回 403 并重定向到其他 URL 的登录【英文标题】:Configure Spring Security to return 403 for REST URLs and redirect to login for other URLs 【发布时间】:2014-07-07 12:45:12 【问题描述】:

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

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

网络上有无数示例如何配置每个方法,但我找不到如何组合这些方法的示例。我所有的 API URL 都以“/api/”开头,所以我需要所有这些 URL 的 403 和所有剩余 URL 的重定向。我该如何设置?

【问题讨论】:

【参考方案1】:

我花了一些时间研究 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>

这可以在 Sping Security 配置中使用:

<http ... entry-point-ref="authenticationEntryPoint">

【讨论】:

【参考方案2】:

我认为你应该只有两个不同的&lt;http pattern="..." ...&gt; 实体,因为,好的,你解决了重定向的问题,但是 csrf 保护呢?还有其他想不出来的问题。

【讨论】:

以上是关于配置 Spring Security 为 REST URL 返回 403 并重定向到其他 URL 的登录的主要内容,如果未能解决你的问题,请参考以下文章

Grails - grails-spring-security-rest - 无法从 application.yml 加载 jwt 机密

使用 Grails 3 和 Spring Security REST 配置 CORS

grails-spring-security-rest 插件和悲观锁定

使用 Spring Security 3.2.4 for Jersey 2.9 REST 服务的全局方法安全性的正确配置是啥?

Spring MVC REST + Spring Security + 基本身份验证

如何使用 Spring Security 和 Angularjs 保护 Spring Rest 服务?