13

SpringSecurity3.0.xを使用しているアプリがあります。そこに私は習慣がありますAuthenticationProvider

public class AppAuthenticationProvider implements AuthenticationProvider {
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        ...
        if (!check1()) throw new UsernameNotFoundException();
        if (!check2()) throw new DisabledException();
        ...
    }

各例外でcutom応答コードを送信したいと思います。たとえば、UsernameNotFoundExceptionの場合は404、DisabledExceptionの場合は403などです。今のところ、Springセキュリティ構成にauthentication-failure-urlがあるので、authenticateの各例外で​​リダイレクトされます。 ()。

4

3 に答える 3

22

認証失敗ハンドラー:

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)) {
    showMessage("BAD_CREDENTIAL");
  } else if (exception.getClass().isAssignableFrom(DisabledException.class)) {
    showMessage("USER_DISABLED");
  }
}

構成 :

<bean id="customAuthenticationFailureHandler"
      class="com.apackage.CustomAuthenticationFailureHandler">
    <property name="defaultFailureUrl" value="/index.jsp"/>
</bean>
<security:http auto-config="true">
  <security:form-login default-target-url="/welcome.jsp" authentication-failure-handler-ref="customAuthenticationFailureHandler" />
</security:http>
于 2012-10-05T14:59:35.987 に答える
15

通常、認証が失敗した理由の詳細を提供することは、攻撃者に有用な情報を提供する可能性があるため、お勧めできません。たとえば、有効なアカウント名をプローブできるようにすることができます。

物事をカスタマイズする必要がある場合は、を使用する代わりに、例外に応じて異なる動作を実装できるカスタムBeanを注入するためにauthentication-failure-url使用できます。authentication-failure-handler-refAuthenticationFailureHandler

于 2012-10-04T19:31:52.367 に答える
5

jspページでの認証のカスタマイズには、以下のタグを使用してください。

<c:if test="${sessionScope[\"SPRING_SECURITY_LAST_EXCEPTION\"].message eq 'Bad credentials'}">
Username/Password entered is incorrect.
</c:if>
<c:if test="${sessionScope[\"SPRING_SECURITY_LAST_EXCEPTION\"].message eq 'User is disabled'}">
Your account is disabled, please contact administrator.
</c:if>
<c:if test="${fn:containsIgnoreCase(sessionScope[\"SPRING_SECURITY_LAST_EXCEPTION\"].message,'A communications error has been detected')}">
Database connection is down, try after sometime.
</c:if>

正しく機能するために、以下のタグライブラリも含めてください

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib uri="http://www.springframework.org/security/tags" prefix="sec"%>

..。

于 2013-05-17T14:53:13.940 に答える