gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 04:06:49 26 4
gpt4 key购买 nike

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

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

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

最佳答案

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

关于spring-security - 配置 Spring Security 为 REST URL 返回 403 并重定向到登录其他 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23739746/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com