2016-12-30 79 views
1

我有2種不同類型的登錄錯誤的:春季安全 - 自定義登錄錯誤消息

  • 不正確的用戶/密碼
  • IP封鎖太多嘗試

眼下春天轉發在這兩種情況下用戶爲www.site.com/login?error。我如何定製登錄行爲,以便根據具體情況將用戶轉發到error1或error2?這種轉發行爲似乎沒有在任何地方明確聲明,我也找不到任何文檔。

回答

1

你要實現自定義AuthenticationFailureHandler,請參閱: Spring security authenticate exceptions handling

如果你只是想將用戶重定向到ERROR1或誤差2,您的實現可以只是一個簡單的重定向方法:

public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler { 

@Override 
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { 
    super.onAuthenticationFailure(request, response, exception); 
    if(exception.getClass().isAssignableFrom(UsernameNotFoundException.class)) { 
    response.sendRedirect("error1") 
    } else if (exception.getClass().isAssignableFrom(LockedException.class)) { 
    response.sendRedirect("error2") 
    } 
} 
} 
+0

如何我是否配置Spring使用該類?我嘗試使用@Component註釋它,並且還嘗試將XML配置添加到pom.xml中(如在鏈接中)。這是在抱怨'認證失敗處理程序ref在這裏是不允許的。 –

+0

@你需要在application-security.xml中配置它,而不是在pom.xml中。 pom.xml主要用於添加依賴項,插件和配置文件。 –

+0

好的,我試着根據我發現的一些例子設置application-security.xml文件,但是我仍然無法使它工作。它看起來沒有關於該文件的文檔應該被定義? –