Spring Security:在401的情况下重定向到登录页面

问题描述 投票:4回答:3

我有一个暴露REST API的应用程序,并使用Spring Security进行保护。有没有办法自动将客户端(从服务器端)重定向到登录页面如果发送到我的服务器的请求导致401 - 未经授权?

spring rest spring-security
3个回答
3
投票

对于基于spring-securityspring-boot应用程序。

定义处理程序bean:

@Component
public class CommenceEntryPoint implements AuthenticationEntryPoint, Serializable {
    private static final long serialVersionUID = 565662170056829238L;

    // invoked when user tries to access a secured REST resource without supplying any credentials,
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException {
        // send a json object, with http code 401,
        // response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");

        // redirect to login page, for non-ajax request,
        response.sendRedirect("/login.html");
    }
}

在安全配置类(例如WebSecurityConfig)中:

自动化bean:

@Autowired
private CommenceEntryPoint unauthorizedHandler; // handle unauthorized request,

指定处理程序

.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and() // excepion handler,

提示:

  • 这仅适用于非ajax请求,
  • 对于ajax请求,最好返回401代码,并让前端处理它。 如果你想使用401响应,在CommenceEntryPoint.commence()只需使用response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");而不是response.sendRedirect()

1
投票

您可以通过在web.xml的error-page元素中指定异常或HTTP状态代码来指定应用程序处理异常或HTTP状态代码的方式

eq:vb.hm

<error-page>
    <error-code>401</error-code>
    <location>/login.html</location>
</error-page>

与处理页面未找到页面的其他HTTP状态代码即404相同。


0
投票

我通过在http节点下将以下元素添加到我的Spring Security XML来解决了这个问题:

<security:access-denied-handler error-page="/#/login"  />
<security:session-management invalid-session-url="/#/login" session-fixation-protection="changeSessionId" />
© www.soinside.com 2019 - 2024. All rights reserved.