Spring安全性自定义AuthenticationException消息

时间:2013-05-26 12:31:10

标签: java spring java-ee spring-security

您好我需要在Spring安全登录表单中添加一个新的异常,除了我想要自己的错误消息之外,一切都运行正常(直到现在它显示“错误的登录/密码”)。

我已从用户名密码验证过滤器覆盖默认尝试验证方法:

@Override
public Authentication attemptAuthentication(final HttpServletRequest request, final HttpServletResponse response)
{
if (!myTest()) {
throw new CustomAuthenticationException("custom message");
}
}

我的例外:

public class CustomAuthenticationException extends AuthenticationException {

    public CustomAuthenticationException(final String message)
    {
        super(message);
    }

    public CustomAuthenticationException(final String message, final Throwable cause)
    {
        super(message, cause);
    }

}

在我的控制器中,我在SPRING_SECURITY_LAST_EXCEPTION下看到了我的异常,但错误消息始终是来自错误凭据的消息,我怎么能改变它?

谢谢

4 个答案:

答案 0 :(得分:14)

您应该尝试定位春季安全信息 尝试将这些行添加到ApplicationContext.xml文件中。其他春季安全豆的位置。

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basename" value="yourFolder/myMessages"/>
</bean>

您应该找到存储<KEY, MESSAGE>的spring默认类。让您的myMessage文件包含相同的KEY和本地化MESSAGE

<小时/> 根据您的评论,您的项目中有messages.properties。因此,您需要做的就是为此属性文件中的每个密钥设置一个MESSAGE,以获得完全本地化的消息:

AbstractAccessDecisionManager.accessDenied= your message in any language
AbstractSecurityInterceptor.authenticationNotFound=
AbstractUserDetailsAuthenticationProvider.badCredentials=
AbstractUserDetailsAuthenticationProvider.credentialsExpired=
AbstractUserDetailsAuthenticationProvider.disabled=
AbstractUserDetailsAuthenticationProvider.expired=
AbstractUserDetailsAuthenticationProvider.locked=
AbstractUserDetailsAuthenticationProvider.onlySupports=
AccountStatusUserDetailsChecker.credentialsExpired=
AccountStatusUserDetailsChecker.disabled=
AccountStatusUserDetailsChecker.expired=
AccountStatusUserDetailsChecker.locked=
AclEntryAfterInvocationProvider.noPermission=
AnonymousAuthenticationProvider.incorrectKey=
BindAuthenticator.badCredentials=
BindAuthenticator.emptyPassword=
CasAuthenticationProvider.incorrectKey=
CasAuthenticationProvider.noServiceTicket=
ConcurrentSessionControlStrategy.exceededAllowed=
DigestAuthenticationFilter.incorrectRealm=
DigestAuthenticationFilter.incorrectResponse=
DigestAuthenticationFilter.missingAuth=
DigestAuthenticationFilter.missingMandatory=
DigestAuthenticationFilter.nonceCompromised=
DigestAuthenticationFilter.nonceEncoding=
DigestAuthenticationFilter.nonceExpired=
DigestAuthenticationFilter.nonceNotNumeric=
DigestAuthenticationFilter.nonceNotTwoTokens=
DigestAuthenticationFilter.usernameNotFound=
JdbcDaoImpl.noAuthority=
JdbcDaoImpl.notFound=
LdapAuthenticationProvider.badCredentials=
LdapAuthenticationProvider.credentialsExpired=
LdapAuthenticationProvider.disabled=
LdapAuthenticationProvider.expired=
LdapAuthenticationProvider.locked=
LdapAuthenticationProvider.emptyUsername=
LdapAuthenticationProvider.onlySupports=
PasswordComparisonAuthenticator.badCredentials=
PersistentTokenBasedRememberMeServices.cookieStolen=
ProviderManager.providerNotFound=
RememberMeAuthenticationProvider.incorrectKey=
RunAsImplAuthenticationProvider.incorrectKey=
SubjectDnX509PrincipalExtractor.noMatching=
SwitchUserFilter.noCurrentUser=
SwitchUserFilter.noOriginalAuthentication=

答案 1 :(得分:2)

在您的messages.properties(或您命名的任何内容)中,添加如下行:

AbstractUserDetailsAuthenticationProvider.badCredentials=The credentials you supplied are invalid.

您不需要CustomAuthenticationException。

答案 2 :(得分:1)

在类路径中创建属性文件,如loginMessage.properties

在该属性文件中,指定

AbstractUserDetailsAuthenticationProvider.badCredentials =输入的用户名/密码不正确。

在applicationContext.xml中添加以下bean,

<bean id="messageSource"   
    class="org.springframework.context.support.ResourceBundleMessageSource">  
    <property name="basenames">  
        <list>
            <value>loginMessage</value>
        </list>
    </property>
</bean>

之后,您将收到输入的用户名/密码错误消息。而不是坏证书

答案 3 :(得分:0)

一种非常简单的方法是在异常处理程序(@ControllerAdvice)中定义您的自定义消息,如下所示:

@ResponseStatus(HttpStatus.UNAUTHORIZED)
@ResponseBody
@ExceptionHandler(value = AuthenticationException.class)
public ResponseModal handleAuthenticationExceptions(AuthenticationException ex, HttpServletResponse response) {
    LOGGER.info("Authentication Exception: {}", ex.getMessage());
    response.addCookie(new Cookie(JWTConfigurer.JWT_TOKEN_COOKIE, null));
    return new ResponseModal(HttpStatus.UNAUTHORIZED.value(), "whatever you want");
}