在Spring Security中,当身份验证失败时,将显示以下预定义的错误消息:
Spring display : Bad credentials
在本文中,我们向您展示如何覆盖以上错误消息并显示您的自定义错误消息。 例如,
Spring display : Bad credentials
You want override it with this message : Invalid username or password
解
Spring Security将消息存储在“ spring-security-core.jar ”内的“ messages.properties ”中,请参见下图:
要覆盖它,请在spring安全性message.properties文件中找到哪个键会生成什么错误消息,然后使用您自己的属性文件重新定义它。
1.覆盖键和消息
创建一个新的属性文件,将其放在项目类路径中,并用您的自定义错误消息覆盖Spring的“键”。 在这种情况下,只需覆盖“ AbstractUserDetailsAuthenticationProvider.badCredentials ”。
文件:mymessages.properties
AbstractUserDetailsAuthenticationProvider.badCredentials=Invalid username or password
2.注册ResourceBundleMessageSource
要加载以上属性文件,请在Spring bean配置文件中定义ResourceBundleMessageSource 。
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>mymessages</value>
</list>
</property>
</bean>
现在,当身份验证失败时,它将显示您的自定义错误消息“ 无效的用户名或密码 ”,而不是默认的“ 错误的凭据 ”。
注意
使用此技巧,您可以轻松覆盖任何Spring Security消息。
下载源代码
下载它– Spring-Security-Display-Custom-Error-Msg.zip (9 KB)
翻译自: https://mkyong.com/spring-security/display-custom-error-message-in-spring-security/




