Issue
I want to throw AuthenticationException
in my overriden attemptAuthentication
from my class that extendsUsernamePasswordAuthenticationFilter
method but I don't know how to do so.
My code:
@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);
}
Is it only meant to be used in try catch clause, If so is there any other way to make filter proceed to unsuccessfulAuthentication
?
Solution
You should create your own subclass of AuthenticationException
, like BadCredentialsException
does.
You can probably create a:
public class NoOpenPortAuthenticationException extends AuthenticationException {
public NoOpenPortAuthenticationException(String msg) {
super(msg);
}
}
And in your code do: throw new NoOpenPortAuthenticationException("No free port found");
Answered By - Marcus Hert da Coregio
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)