java Spring security 自定义 AuthenticationException 消息
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16759264/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring security custom AuthenticationException message
提问by Benoit Vanalderweireldt
Hi i needed to add a new exception in Spring security login form, everything work perfectly except that i want to have my own error message (until now it display the "wrong login/password" one).
嗨,我需要在 Spring 安全登录表单中添加一个新异常,除了我想拥有自己的错误消息(直到现在它显示“错误的登录名/密码”)之外,一切都完美无缺。
I have override default attempt authentication method from Username password Authentication Filter :
我已经从用户名密码身份验证过滤器覆盖默认尝试身份验证方法:
@Override
public Authentication attemptAuthentication(final HttpServletRequest request, final HttpServletResponse response)
{
if (!myTest()) {
throw new CustomAuthenticationException("custom message");
}
}
My exception :
我的例外:
public class CustomAuthenticationException extends AuthenticationException {
public CustomAuthenticationException(final String message)
{
super(message);
}
public CustomAuthenticationException(final String message, final Throwable cause)
{
super(message, cause);
}
}
In my controller i see my exception under SPRING_SECURITY_LAST_EXCEPTION but the error message is always the one from bad credentials, how could i change that ?
在我的控制器中,我在 SPRING_SECURITY_LAST_EXCEPTION 下看到我的异常,但错误消息总是来自错误的凭据,我该如何更改?
Thank you
谢谢
回答by Matin Kh
You should try LOCALIZING SPRING SECURITY MESSAGES.
Try adding these lines into your ApplicationContext.xml
file. Where the rest of your spring security beans are.
您应该尝试LOCALIZING SPRING SECURITY MESSAGES。
尝试将这些行添加到您的ApplicationContext.xml
文件中。其余的 spring 安全 bean 在哪里。
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename" value="yourFolder/myMessages"/>
</bean>
You should find your spring default class which <KEY, MESSAGE>
are stored. Have your myMessage
file with the same KEY
s and localized MESSAGE
s.
您应该找到<KEY, MESSAGE>
存储的spring 默认类。让您的myMessage
文件具有相同的KEY
s 和本地化的MESSAGE
s。
根据您的评论,您
messages.properties
messages.properties
的项目中有一个。所以你需要做的就是MESSAGE
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=
回答by holmis83
In your messages.properties (or whatever you named it), add a line like:
在您的 messages.properties(或您命名的任何内容)中,添加如下一行:
AbstractUserDetailsAuthenticationProvider.badCredentials=The credentials you supplied are invalid.
You don't need a CustomAuthenticationException.
您不需要 CustomAuthenticationException。
回答by softmage99
Create a property file in class path like loginMessage.properties
在类路径中创建一个属性文件,如 loginMessage.properties
In that property file, specify
在该属性文件中,指定
AbstractUserDetailsAuthenticationProvider.badCredentials=Username/Password entered is incorrect.
AbstractUserDetailsAuthenticationProvider.badCredentials=输入的用户名/密码不正确。
Add the following bean in your applicationContext.xml,
在 applicationContext.xml 中添加以下 bean,
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>loginMessage</value>
</list>
</property>
</bean>
After that, u'll get message like Username/Password entered is incorrect. instead of Bad Credentials
之后,您会收到类似用户名/密码输入不正确的消息。而不是坏凭证
回答by doannx
A very simple way is defining your custom message in exception handler (@ControllerAdvice), as following:
一种非常简单的方法是在异常处理程序 (@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");
}