spring-security 如何抛出Spring安全AuthenticationException或继续进行不成功的身份验证

qoefvg9y  于 2022-11-11  发布在  Spring
关注(0)|答案(1)|浏览(165)

我想从我的类中抛出AuthenticationException到我的覆盖attemptAuthentication中,这个类扩展了UsernamePasswordAuthenticationFilter方法,但是我不知道怎么做。
我的代码:

@Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
        if(portService.getOpenPort()==null){
            //'AuthenticationException' is abstract; cannot be instantiated
            throw new AuthenticationException("No free port found");
        }
        return authenticationManager.authenticate(authenticationToken);
    }

它是否仅用于try catch子句,如果是,是否有其他方法使过滤器继续unsuccessfulAuthentication

stszievb

stszievb1#

您应该像BadCredentialsException一样创建自己的AuthenticationException子类。
您可以创建:

public class NoOpenPortAuthenticationException extends AuthenticationException {

    public NoOpenPortAuthenticationException(String msg) {
        super(msg);
    }

}

并在代码中执行以下操作:throw new NoOpenPortAuthenticationException("No free port found");

相关问题