首页 > 解决方案 > Spring MVC 视图控制器重定向

问题描述

是否可以不重定向到没有查询参数的视图?我有一个login视图,我想login?error在登录失败时重定向到浏览器中的 url。我有我自己的AuthenticationFailureHandler

public class SomeCustomHandler implements AuthenticationFailureHandler {
  private final SimpleUrlAuthenticationFailureHandler authenticationFailureHandler = new SimpleUrlAuthenticationFailureHandler("/login?error");

  @Override
  public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
    authenticationFailureHandler.onAuthenticationFailure(request, response, exception);
  }
}

配置在WebSecurityConfigurerAdapter

@Override
protected void configure(HttpSecurity http) throws Exception {
  http
      .requestMatchers()
      .antMatchers("/login", "/oauth/authorize")
    .and()
      .authorizeRequests()
      .anyRequest().authenticated()
    .and()
      .formLogin()
      .loginPage("/login")
      .failureHandler(new SomeCustomHandler())
    .permitAll();
}

但是当登录失败时,返回login?error在用户中被重定向到login忽略?error参数。

在此处输入图像描述

这是我的 MvcWebConfigurer:

@Override
public void addViewControllers(ViewControllerRegistry registry) {
  registry.addViewController("/login/**").setViewName("login"); 
}  

标签: javaspringspring-bootspring-mvcspring-security

解决方案


我认为你可以尝试做这样的事情:

public class SomeCustomHandler implements AuthenticationFailureHandler {
    private final SimpleUrlAuthenticationFailureHandler authenticationFailureHandler = new SimpleUrlAuthenticationFailureHandler("/login?error");

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        if(request.getPathInfo().startsWith("/login") && !request.getParameterMap().isEmpty()) {
            authenticationFailureHandler.setUseForward(true);
        }
        authenticationFailureHandler.onAuthenticationFailure(request, response, exception);
    }
}

推荐阅读