【问题标题】:Spring MVC view controller redirectionSpring MVC 视图控制器重定向
【发布时间】:2019-07-26 12:25:47
【问题描述】:

是否可以不重定向到没有查询参数的视图?我有一个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"); 
}  

【问题讨论】:

  • 请将 registry.addViewController("/login/**").setViewName("login"); 更改为 registry.addViewController("/login").setViewName("login"); 并重试并告诉我
  • 很遗憾还是一样。
  • 尝试添加登录视图?错误registry.addViewController("/login?error").setViewName("errorpage")
  • 在configure(HttpSecurity http)中添加.antMatchers("/login?error"").permitAll()
  • 我想要一个/login 页面,因为我会有多个错误原因,例如?error=bad-credentials 或 ?error=locked-account 并且在 /login 页面上将有一个 <div> 带有基于作为查询参数传递的错误类型的错误消息。创建单独的errorpage 会导致为每种错误类型创建新页面,这些页面之间的唯一区别是错误消息。

标签: java spring spring-boot spring-mvc spring-security


【解决方案1】:

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

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);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-22
    • 2018-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多