Spring security custom AuthenticationException message

試著忘記壹切 提交于 2019-12-18 13:27:54

问题


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).

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 ?

Thank you


回答1:


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.

<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 KEYs and localized MESSAGEs.


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



回答2:


In your messages.properties (or whatever you named it), add a line like:

AbstractUserDetailsAuthenticationProvider.badCredentials=The credentials you supplied are invalid.

You don't need a CustomAuthenticationException.




回答3:


Create a property file in class path like loginMessage.properties

In that property file, specify

AbstractUserDetailsAuthenticationProvider.badCredentials=Username/Password entered is incorrect.

Add the following bean in your applicationContext.xml,

<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




回答4:


A very simple way is defining your custom message in exception handler (@ControllerAdvice), as following:

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


来源:https://stackoverflow.com/questions/16759264/spring-security-custom-authenticationexception-message

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!