首页 > 解决方案 > 如何在 UsernamePasswordAuthenticationFilter 的上下文中交换已弃用的 getExtraInformation()?

问题描述

我正在将旧的 Spring 2.5 代码升级到 Spring 3.0(作为第一步)。在此期间,我发现了以下问题:

AuthenticationException 类型的方法 getExtraInformation() 已弃用

关键是这发生在以下子类中UsernamePasswordAuthenticationFilter

@Override
protected void unsuccessfulAuthentication(final HttpServletRequest req, final HttpServletResponse res, final AuthenticationException authException) throws IOException, ServletException
 {
  req.setAttribute("exception", authException);
  super.unsuccessfulAuthentication(req, res, authException);
  if (authException instanceof CredentialsExpiredException)
   {
    final User user = ((UserDetailsImpl)authException.getExtraInformation()).getUser();
    if (user.getCredentials().getUserCannotChange())
     {
      throw authException;
     }
    req.setAttribute("user", user);
    req.setAttribute("msg", this.messages.getMessage("AbstractUserDetailsAuthenticationProvider.credentialsExpiredPleaseChange"));
   }
 }

直到现在我发现没有办法以另一种方式获得用户。所以我的问题是当用户不再通过异常额外信息传输时如何获取用户?

关键是这里需要用户,因为必须做出决定是只重新抛出异常还是应该向用户显示消息。

顺便提一句。我没有找到创建CredentialsExpiredExceptionwith的代码ExtraInformation,所以我假设这将由 Spring/Spring Security Framework 完成?

标签: springspring-security

解决方案


我认为当 Spring Security 检查是否存在CredentialsExpiredException. 假设您使用的是默认设置,CredentialsExpiredExceptionpostAuthenticationChecks UserDetailsCheckerDaoAuthenticationProvider. 默认实现是DefaultPostAuthenticationChecks你可以用你的覆盖它:

public class MyPostAuthenticationChecks extends DefaultPostAuthenticationChecks {

      public void check(UserDetails user) {
            UserDetailsImpl userImpl = (UserDetailsImpl)user;
            if (user.getCredentials().getUserCannotChange()){
                throw new CredentialsExpiredException("Some customized error message blalblbal");
            }else{
                super.check(user);
            }
        }
}

推荐阅读