Spring security custom AuthenticationException message

Hi, I need to add a new exception to the Spring login form, everything works fine, except that I want to have my own error message (so far it displays "incorrect username / password").

I overridden the default authentication method of the attempt from the username. 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 one of the bad credentials, how can I change this?

thanks

+5
source share
4 answers

You should try LOCALIZING SPRING SAFETY MESSAGES .
Try adding these lines to your ApplicationContext.xml file. Where is your remaining protection SPRING beans.

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

You should find your default SPRING class, which is stored <KEY, MESSAGE> . Create a myMessage file with the same KEY and localized MESSAGE s.


Based on your comment, you have messages.properties in your project. So, all you have to do is have a MESSAGE for each of these keys inside this properties file in order to have fully localized messages:
 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= 
+12
source

In your .properties posts (or whatever you called it) add a line like:

 AbstractUserDetailsAuthenticationProvider.badCredentials=The credentials you supplied are invalid. 

You do not need a CustomAuthenticationException.

+2
source

Create a properties file in the class path, for example loginMessage.properties

In this properties file, specify

AbstractUserDetailsAuthenticationProvider.badCredentials = Username / password is incorrect.

Add the following bean to your applicationContext.xml,

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

After that, you will receive a message similar to the username / password entered incorrectly. instead of bad credentials

+1
source

A very simple way is to define your custom message in the exception handler (@ControllerAdvice) as follows:

 @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"); } 
0
source

Source: https://habr.com/ru/post/1482816/