Spring 无法获取登录失败原因(仅弹出BadCredential异常)

Spring 无法获取登录失败原因(仅弹出BadCredential异常),spring,spring-mvc,spring-security,Spring,Spring Mvc,Spring Security,如果用户身份验证失败,尝试各种方法从spring获取自定义消息 使用 要显示错误消息,我使用以下行 JSP 让我简要介绍一下预期的信息 如果用户输入了错误的凭据,则应获得 “无效凭据” 如果用户帐户处于非活动状态,则应获取 “您的帐户未激活” 如果用户超过允许的 尝试他的帐户将被锁定,他将获得“您的帐户已关闭” “锁定” 如果我的实现不正确,请让我知道应该做哪些更改 如果要覆盖AuthenticationFailureHandler,可以扩展SimpleRuthenticationFailu

如果用户身份验证失败,尝试各种方法从spring获取自定义消息

使用

要显示错误消息,我使用以下行

JSP


让我简要介绍一下预期的信息

  • 如果用户输入了错误的凭据,则应获得 “无效凭据”

  • 如果用户帐户处于非活动状态,则应获取 “您的帐户未激活”

  • 如果用户超过允许的 尝试他的帐户将被锁定,他将获得“您的帐户已关闭” “锁定”
  • 如果我的实现不正确,请让我知道应该做哪些更改


    如果要覆盖AuthenticationFailureHandler,可以扩展
    SimpleRuthenticationFailureHandler
    ,它已经有了保存异常的方法

    protected final void saveException(HttpServletRequest request, AuthenticationException exception) {
                if (forwardToDestination) {
                    request.setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, exception);
                } else {
                    HttpSession session = request.getSession(false);
    
                    if (session != null || allowSessionCreation) {
                        request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, exception);
                    }
                }
            }
    
    当您将异常保存到请求或会话时,您可以获得消息

    ${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message}
    
    @Service("userDetailsService")
    public class CustomUserDetailsService implements UserDetailsService {
    @Override
        public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
            logger.info("Getting access details for user : {}", username);
            UserDto userDto = null;
            boolean accountNonExpired = true;
            boolean accountNonLocked = true;
            boolean credentialsNonExpired = true;
            boolean enabled = true;
            try {
                userDto = userService.loginUser(username);
                if (userDto == null) {
                    throw new UsernameNotFoundException("User not found");
                }
                if (Active.Y != userDto.getActive()) {
                    enabled = false;  
                    throw new BadCredentialsException("User account is inactive");
                }
            } catch (BaseException be) {
                throw new BadCredentialsException(be.getMessage().toLowerCase());
            }
    
            UserContext context = new UserContext();
            context.setLoginId(username);
            context.setName(userDto.getName());
            context.setPrincipleId(userDto.getId());
    
            List<GrantedAuthority> grantedAuthorities = getGrantedAuthorities(userDto);
            String password = getActivePassword(userDto);
            accountNonExpired = isAccountActive(userDto);
            accountNonLocked = isAccountUnlocked(userDto);
            credentialsNonExpired = isCredentialsActive(userDto); 
    
            return new UserLoginDetails(grantedAuthorities, password, username, accountNonExpired, accountNonLocked, credentialsNonExpired, enabled, context);
        }
    }
    
       @Component
        public class CustomAuthenticationFailureHandler implements AuthenticationFailureHandler {
       private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();
    
        @Autowired
        UserService userService;
    
        @Override
        public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException authenticationException) throws IOException, ServletException {
            try {
                // execute it when user enters wrong password, i.e loginAttempt ...
            } catch (Exception e) {
              // TODO: something
    
            }
            // TODO: how do I send message, if authenticationException.
            redirectStrategy.sendRedirect(request, response, "/login?error");
            // clearAuthenticationAttributes(request);
        }
    
        protected void clearAuthenticationAttributes(HttpServletRequest request) {
            HttpSession session = request.getSession(false);
            if (session == null) {
                return;
            }
            session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION);
        }
    }
    
    <c:set var="errorMessage" value="${sessionScope[\"SPRING_SECURITY_LAST_EXCEPTION\"].message}" />
    
    protected final void saveException(HttpServletRequest request, AuthenticationException exception) {
                if (forwardToDestination) {
                    request.setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, exception);
                } else {
                    HttpSession session = request.getSession(false);
    
                    if (session != null || allowSessionCreation) {
                        request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, exception);
                    }
                }
            }
    
    ${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message}