Spring Security:在出现 401 时重定向到登录页面

Sam*_*nia 6 rest spring spring-security

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

Eri*_*ang 7

对于spring-security基于spring-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");
    }
}
Run Code Online (Sandbox Code Playgroud)

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

自动装配 bean:

@Autowired
private CommenceEntryPoint unauthorizedHandler; // handle unauthorized request,
Run Code Online (Sandbox Code Playgroud)

指定处理程序:

.exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and() // excepion handler,
Run Code Online (Sandbox Code Playgroud)

提示:

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

  • 您不需要创建自己的组件。相反,你可以使用这个:`.exceptionHandling().authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/"))` (3认同)

Sam*_*nia 0

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

<security:access-denied-handler error-page="/#/login"  />
<security:session-management invalid-session-url="/#/login" session-fixation-protection="changeSessionId" />
Run Code Online (Sandbox Code Playgroud)