spring security登录自定义错误信息

首先,spring security的authentication-provider默认加载的是DaoAuthenticationProvider类。然后找到DaoAuthenticationProvider的父类AbstractUserDetailsAuthenticationProvider的authenticate方法,发现了这段代码。
try {
    user = retrieveUser(username, (UsernamePasswordAuthenticationToken) authentication);
} catch (UsernameNotFoundException notFound) {
    logger.debug("User '" + username + "' not found");

    if (hideUserNotFoundExceptions) {
        throw new BadCredentialsException(messages.getMessage("AbstractUserDetailsAuthenticationProvider.badCredentials", "Bad credentials"));
    } else {
        throw notFound;
    }
}


然后可以通过新建一个properties来覆盖spring security默认的错误信息,security.properties内容如下:
AbstractUserDetailsAuthenticationProvider.badCredentials=用户名或密码错误

再在bean里注入:
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basenames">
        <list>
    <value>security</value>
</list>
    </property>
    <property name="defaultEncoding" value="utf8" />
</bean>

最后在页面上就可以通过${SPRING_SECURITY_LAST_EXCEPTION.message}来获取错误信息

猜你喜欢

转载自javahuhui.iteye.com/blog/2229403