2012-11-07 2 views
2

사용자 인증에 스프링 보안을 사용하고 있습니다. 커스텀 인증 공급자를 만들었고 공급자로부터 에러 메시지를 어떻게 얻을 수 있는지 궁금합니다. 이것은 내 사용자 지정 인증 공급자에서 인증합니다() 방법 :스프링 로그인시 오류 메시지 표시

@Override 
public Authentication authenticate(Authentication authentication) throws AuthenticationException { 
    UserProfile profile = userProfileService.findByEmail(authentication.getPrincipal().toString()); 

    if(profile == null){ 
     throw new UsernameNotFoundException(String.format("Invalid credentials", authentication.getPrincipal())); 
    } 

    String suppliedPasswordHash = DigestUtils.shaHex(authentication.getCredentials().toString()); 

    if(!profile.getPasswordHash().equals(suppliedPasswordHash)){ 
     throw new BadCredentialsException("Invalid credentials"); 
    } 

    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(profile, null, profile.getAuthorities()); 

    return token; 
} 

이 내 형태 :

<form name='f' action="<c:url value='j_spring_security_check' />" method='POST'> 
<div id="data-entry-form"> 

    <div class="form-entry"> 
     <label><spring:message code="login.form.label.email"/></label> 
     <input type='text' name='j_username' value=''> 
    </div> 
    <div class="form-entry"> 
     <label><spring:message code="login.form.label.password"/></label> 
     <input type='password' name='j_password'/> 
    </div> 
    <div class="form-entry"> 
     <input type="submit" value="Verzenden"/> 
    </div> 
</div> 

어떻게 내 양식에 오류 메시지를받을까요? 로그인 버튼을 누르는 순간부터 스프링이 대신 처리하므로 오류 메시지를 생성 할 수있는 유일한 방법은 authenticate() 메서드입니다.

답변

3

메시지를 가져올 수 있어야한다고 생각합니다. "표준"인증자를 사용하는 것과 같은 방식입니다. 인증 프로세스에서 예외 (또는 둘 이상)가 발생하면 마지막 예외는 세션 속성 SPRING_SECURITY_LAST_EXCEPTION에 저장됩니다. 당신이 컨트롤러가있는 경우 당신은 아마 컨트롤러에서 메시지를받을 만 통과해야한다, 물론

<%=((Exception) request.getSession().getAttribute("SPRING_SECURITY_LAST_EXCEPTION")).getMessage()%>; 

:

그래서, JSP에서 마지막 예외 메시지를 얻기 위해이 같은 것을 사용할 수 있습니다 jsp에 문자열.

<c:if test="${param.auth eq 'failure'}"> 
    <div class="error"> 
    <c:out value="${SPRING_SECURITY_LAST_EXCEPTION.message}" /> 
    </div> 
</c:if> 

주 당신이 당신의 스프링이에 설정할 수있는 특수 매개 변수를 통해 오류가 여부를 감지 할 필요가 :이처럼 그것을 해결할 수 있었다

+0

내가 역 참조했던 모든 변수에 대한 검사를 추가 한 후에도이 솔루션을 사용하여 JSP에서 'NullPointerException'을 많이 사용하고있었습니다. 그래서 더 좋은 솔루션을 발견하고 내 대답으로 게시했습니다. – vadipp

1

) 이것은 단지 예입니다

<security:form-login [...] authentication-failure-url="/login?auth=failure" />