2017-02-11 63 views
2

我想配置我自己的成功和身份验证失败处理程序。在身份验证失败时,我想用请求参数重定向回我的登录页面,此参数的出现将在我的登录页面上输出错误消息。但是,尽管出现错误,我将重定向回到我的登录页面,但请求参数始终为null。下面身份验证失败重定向请求参数不起作用

代码:

protected void configure(HttpSecurity http) throws Exception { 
    http 
     .csrf().disable() 
     .authorizeRequests() 
      .antMatchers("/").permitAll() 
      .antMatchers("/login").permitAll() 
      .anyRequest().authenticated() 
      .and() 
     .formLogin() 
      .loginPage("/login.html").permitAll() 
      .usernameParameter("username") 
      .passwordParameter("password")            
      .loginProcessingUrl("/login") 
      .successHandler(successHandler()) 
      .failureHandler(handleAuthenticationFailure()); 
} 

@Autowired 
@Override 
protected void configure(AuthenticationManagerBuilder auth) throws Exception { 
    //database checks 
} 
}; 
} 

/** 
* Authentication success handler defines action when successfully authenticated 
* @return 
*/ 
@Bean 
public AuthenticationSuccessHandler successHandler(){ 
    return new AuthenticationSuccessHandler() { 

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

      // custom auth success here 
      httpResponse.setStatus(HttpServletResponse.SC_OK); 
      SavedRequest savedRequest = (SavedRequest) httpRequest.getSession().getAttribute("SPRING_SECURITY_SAVED_REQUEST"); 
      httpResponse.sendRedirect(savedRequest.getRedirectUrl()); 
     } 
    }; 
} 

@Bean 
public AuthenticationFailureHandler handleAuthenticationFailure() { 
    return new SimpleUrlAuthenticationFailureHandler() { 

     @Override 
     public void onAuthenticationFailure(HttpServletRequest httpRequest, HttpServletResponse httpResponse, 
              AuthenticationException authenticationException) throws IOException, ServletException { 

      // custom failure code here 
      setDefaultFailureUrl("/login.html?error=fail"); 
      super.onAuthenticationFailure(httpRequest, httpResponse, authenticationException); 
     } 
    }; 
} 
+1

你如何获得帕拉姆?你能否跟踪网络以查找是否用'error = fail'请求了URL? – chaoluo

回答

2

试试这个:

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

    // ....... 

    response.sendRedirect("/login.html?error=fail");  
} 

更新:

这是非常重要的是, “/login.html?error=fail” 加到authorizeRequests()部分,否则控制器将不会拾取错误参数。

更换.antMatchers("/login").permitAll().antMatchers("/login**").permitAll()

0

(登录时失败了,并加入了一些请求参数到URL重定向它没有PARAMS到登录页面在我的情况),也有使用参数的问题。

这解决了我的问题

.antMatchers("/login**").permitAll()