当前位置: 首页 > 知识库问答 >
问题:

登录成功后重定向到原始页面返回原始数据而不是URL名称

咸晨
2023-03-14

我正在使用Spring Security和前端reactJS的Spring Boot构建一个应用程序。我的代码可以很好地进行身份验证。但现在我计划将用户重定向到他以前请求的页面,以防他再次登录。

我可以从成功处理程序中提取 targetUrl,即上一页,但是当我在 UI 上执行控制台.log(数据)时。我得到的是原始的html数据而不是URL名称。我不知道为什么以及如何打开这样的原始 html 代码,或者我可以只从成功处理程序发送 html URL 名称,而不是发送完整的原始 html 代码?任何意见都受到高度赞赏。

预期console.log(数据)-https://localhost:8080/addpage.html

实际控制台. log(数据)-addpage.html的原始html数据

应用程序安全.java

public class ApplicationSecurity extends WebSecurityConfigurerAdapter {
@Autowired
private UserDetailsService userDetailsService;

@Autowired
private RESTAuthenticationEntryPoint authenticationEntryPoint;
@Autowired
private RESTAuthenticationFailureHandler authenticationFailureHandler;
@Autowired
private RESTAuthenticationSuccessHandler authenticationSuccessHandler;
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
    return new BCryptPasswordEncoder();
}


@Override
protected void configure(HttpSecurity http) throws Exception {

    http
    .authorizeRequests()
        .antMatchers("/CSS/*").permitAll()
        .antMatchers("/JS/*").permitAll()
        .antMatchers("/login.html").permitAll()
        .antMatchers("/*").authenticated()
        .and()
        .sessionManagement().maximumSessions(5).and().invalidSessionUrl("/login.html");
    http.csrf().disable();
    http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint);
    http.formLogin().successHandler(authenticationSuccessHandler);
    http.formLogin().failureHandler(authenticationFailureHandler);
    http.logout().logoutSuccessUrl("/login.html");

}

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception{
    auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());

}
}

RESTAuthenticationSuccessHandler.java

@Component
 public class RESTAuthenticationSuccessHandler extends 
 SavedRequestAwareAuthenticationSuccessHandler   {

  private RequestCache requestCache = new HttpSessionRequestCache();

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) throws IOException, ServletException {

    SavedRequest savedRequest = requestCache.getRequest(request, response);

    System.out.println(savedRequest);

     if (savedRequest == null) {
         HttpSession session = request.getSession();
         if (session != null) {
             String redirectUrl = (String) session.getAttribute("url_prior_login");
             if (redirectUrl != null) {
                 session.removeAttribute("url_prior_login");
                 getRedirectStrategy().sendRedirect(request, response, redirectUrl);
             } else {
                 super.onAuthenticationSuccess(request, response, authentication);
             }
         } else {
             super.onAuthenticationSuccess(request, response, authentication);
         }

         return;
     }

     String targetUrlParameter = getTargetUrlParameter();
     System.out.println(targetUrlParameter);
     if (isAlwaysUseDefaultTargetUrl()
             || (targetUrlParameter != null && StringUtils.hasText(request.getParameter(targetUrlParameter)))) {
         requestCache.removeRequest(request, response);
         super.onAuthenticationSuccess(request, response, authentication);

         return;
     }

     clearAuthenticationAttributes(request);

     // Use the DefaultSavedRequest URL
     String targetUrl = savedRequest.getRedirectUrl();
     System.out.println(targetUrl);
     logger.debug("Redirecting to DefaultSavedRequest Url: " + targetUrl);
     getRedirectStrategy().sendRedirect(request, response, targetUrl);


     }


 }

UI代码:

 $.ajax({
                type: "POST",
                url: "/login",
                data: data,
                success: function(data){
                    console.log(data);
                }.bind(this),
                error:function(data)
                {
                    alert(data.responseJSON.message);
                }
            });

安慰log(data)-返回targetURL的原始html代码,我无法将其作为html文件打开。我需要successhandler中targetURL返回的html文件名,以便我可以使用window.location。href打开文件

共有2个答案

夏侯阳
2023-03-14

听起来像是MIME类型的问题。使用Chrome检查检查您的Web流量并确保您的标头设置正确:

响应标头:

内容类型:text/html;charset=utf-8

请求标头:

接受:text/html

等。

钱弘壮
2023-03-14

您可以将重定向 URL 返回到响应。

public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
    Authentication authentication) throws IOException, ServletException {
 // ... get target url
 String targetUrl = "";
 try {
            response.setStatus(HttpServletResponse.OK);
            PrintWriter writer = response.getWriter();
            writer.write(targetUrl);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            // ignore
            logger.error(e.getMessage(), e);
        } 

}

 类似资料:
  • 我正在开发一个应用程序,它允许用户浏览网站并从任何页面登录(登录链接位于公共标题中)。成功登录后,用户当前将从登录页面重定向到根url。 redirect_to原始页面会更友好。我试图将原始页面的命名路由存储到会话中,但这些似乎是对象,因此无法通过。此外,并非所有路由都带有指定的助手。另一方面,当我将文字路径作为字符串传递给redirect_to时,例如“订单/索引”,Rails将 /action

  • 这似乎是一个非常基本的流程,而且Laravel有很多很好的基本解决方案,我觉得我错过了一些东西。 用户单击需要身份验证的链接。Laravel的身份验证过滤器启动并将它们路由到登录页面。用户登录,然后转到他们试图在“身份验证”过滤器启动之前进入的原始页面。 有没有一个好方法可以知道他们最初想要到达的页面?由于Laravel是拦截请求的人,我不知道它是否会在用户登录后跟踪某个地方以方便路由。 如果没有

  • 在我的Laravel应用程序中,我有一个只能由Auth用户访问的私人页面。我也使用社交登录,所以当用户未登录就进入私人页面时,Laravel会将用户发送到登录页面,成功登录后,用户会被发送回原始目的地(私人页面)。只有当用户通过Laravel内置认证系统登录时,但当用户通过社交登录方法登录时,用户将被引导到主页。 这是我登录后的社交登录处理程序: 如果用户在会话中出现,我如何将其发送到原始目的地,

  • 现在,当我试图访问以下URL:时,它会将我重定向到页面。 如何进行配置以返回而不是重定向到登录页?

  • 我们的团队正在使用Spring boot(2.2.2)开发一个web应用程序。它使用Spring security来处理登录过程。我们希望应用程序在登录前重定向回页面(例如,用户访问)http://example.com/foo/bar - 除了应用程序偶尔指向默认页面(例如,http://example.com)而不是登录前的页面。发生这种情况时,登录前的页面似乎没有保存在会话中(根据我的队友的

  • 问题内容: 我正在做一个简单的论坛,由一系列论坛组成,每个论坛分别代表首页,主题,postitit,登录名和用户列表页面。在某些页面上,当用户未登录时会出现一个链接。 我想要实现的是在登录后触发重定向(在RequestDispatcher上使用forward()),以便浏览器返回到用户在单击登录链接之前所在的页面。为此,我看到了两种解决方案。 第一种解决方案是使用带有登录按钮的HTML 和一个不可