【问题标题】:Spring security custom AuthenticationException messageSpring Security 自定义 AuthenticationException 消息
【发布时间】:2013-05-21 11:44:14
【问题描述】:

您好,我需要在 Spring 安全登录表单中添加一个新异常,一切正常,除了我想拥有自己的错误消息(直到现在它显示“错误的登录名/密码”)。

我已经覆盖了用户名密码验证过滤器中的默认尝试验证方法:

@Override
public Authentication attemptAuthentication(final HttpServletRequest request, final HttpServletResponse response)
{
if (!myTest()) {
throw new CustomAuthenticationException("custom message");
}
}

我的例外:

public class CustomAuthenticationException extends AuthenticationException {

    public CustomAuthenticationException(final String message)
    {
        super(message);
    }

    public CustomAuthenticationException(final String message, final Throwable cause)
    {
        super(message, cause);
    }

}

在我的控制器中,我在 SPRING_SECURITY_LAST_EXCEPTION 下看到了我的异常,但错误消息始终是来自错误凭据的消息,我该如何更改?

谢谢

【问题讨论】:

  • 您需要在登录页面或日志文件中显示不同的消息吗?如果是登录页面需要配置:<form-login login-page="/login.jsp" authentication-failure-url="/login.jsp?login_error=1"/>
  • 在登录页面中,他们正在为每个 AuthenticationException(BadCredentialsException,LockedException... 参见 org.springframework.security.authentication)从异常到自定义消息的某个位置映射,我想显示我的自己的错误信息。

标签: java spring jakarta-ee spring-security


【解决方案1】:

您应该尝试本地化春季安全消息
尝试将这些行添加到您的 ApplicationContext.xml 文件中。其余的 Spring Security bean 在哪里。

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

您应该找到存储了&lt;KEY, MESSAGE&gt; 的spring 默认类。让您的myMessage 文件具有相同的KEYs 和本地化的MESSAGEs。


根据您的评论,您的项目中有一个messages.properties。因此,您需要做的就是在此属性文件中为每个这些键设置一个 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=

【讨论】:

  • 是的,我已经有一个消息资源,但是我的自定义异常的关键是什么?
  • 为您更新了答案。您所要做的就是为每个键设置一个MESSAGE
  • 为什么不提供反馈?如果它解决了你的问题,你可以接受它作为答案,如果你觉得它有用,你可以推广它。
  • 嗨,Matin,请告诉我有关根据区域设置获取消息的信息。我无法在中文区域设置中获取中文消息。
  • 亲爱的@MatinKh,你能回答我的问题吗? stackoverflow.com/questions/63339729/…
【解决方案2】:

在你的messages.properties(或任何你命名的)中,添加如下一行:

AbstractUserDetailsAuthenticationProvider.badCredentials=The credentials you supplied are invalid.

您不需要 CustomAuthenticationException。

【讨论】:

  • 在 Spring Boot 上为我工作
【解决方案3】:

在类路径中创建一个属性文件,例如 loginMessage.properties

在该属性文件中,指定

AbstractUserDetailsAuthenticationProvider.badCredentials=输入的用户名/密码不正确。

在您的 applicationContext.xml 中添加以下 bean,

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

之后,您会收到类似用户名/密码输入不正确的消息。而不是坏凭据

【讨论】:

    【解决方案4】:

    一种非常简单的方法是在异常处理程序(@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");
    }
    

    【讨论】:

      猜你喜欢
      • 2015-07-29
      • 2020-05-26
      • 2017-05-15
      • 1970-01-01
      • 2013-06-30
      • 2021-06-06
      • 2014-08-11
      • 2012-10-10
      • 2019-09-22
      相关资源
      最近更新 更多