首页 > 解决方案 > 如何在 Spring Security 中处理从 authenticationSuccessHandler 重定向到 Angular

问题描述

我正在尝试实现记住我的功能。问题是 Angular 以自己的方式处理路由,因此我无法从 Spring 应用程序重定向到 Angular 应用程序的特定路径。我通过发送带有重定向消息的响应来解决这个问题,然后 Angular 应用程序解析消息并重定向到特定路径。它工作得很好,但是在配置安全性时,它的工作方式略有不同。

例如,当我尝试登录时,我覆盖了 successHandler,因为默认情况下 Spring 想要重定向到某个 url,而 Angular 无法处理它。

.and()
    .formLogin()
        .loginPage("/")
        .loginProcessingUrl("/login")
        .successHandler((request, response, authentication) -> {
            AuthenticatedUser user = new AuthenticatedUser(
                    authentication.getName(),
                    authentication.isAuthenticated()
            );
            log.info("Authenticated {}", user);
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            response.getWriter().print(objectMapper.writeValueAsString(user));
        })
        .failureHandler((request, response, exception) -> {
            response.sendError(HttpServletResponse.SC_FORBIDDEN, "Wrong username and/or password");
        })

这很好用,但是当涉及到rememberMeauthenticationSuccessHandler时,它的工作方式不同。代码看起来与登录成功处理程序相同。

.and()
    .rememberMe()
        .authenticationSuccessHandler((request, response, authentication) -> {
        AuthenticatedUser user = new AuthenticatedUser(
                    authentication.getName(),
                    authentication.isAuthenticated()
            );
            log.info("Authenticated {}", user);
            response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            response.getWriter().print(objectMapper.writeValueAsString(user));
            redirectStrategy.sendRedirect(request, response, "");
        }).key("test")

但是当我以这种方式执行此操作并使用应用程序关闭选项卡并再次打开它时,Spring 会使用我的 AuthenticatedUser 为我提供 json 响应。

春天的回应

我还尝试在 authenticationSuccessHandler 中使用RedirectStrategy重定向到 index.html,root 但它也不起作用。

redirectStrategy.sendRedirect(request, response, "index.html");
redirectStrategy.sendRedirect(request, response, "/");
redirectStrategy.sendRedirect(request, response, "");

我在 Spring 应用程序日志中看到我的 rememberMe 工作正常,但我不知道如何正确重定向,该用户不需要再次登录。

标签: angularspringspring-securityangular-routing

解决方案


推荐阅读