我创建了一个自定义异常类
public class DataException extends Exception {
private final String errorCode;
private final String errorMessage;
private final HttpStatus httpStatus;
/**
*/
public DataException( String errorCode, String errorMessage,
HttpStatus httpStatus )
{
this.errorCode = errorCode;
this.errorMessage = errorMessage;
this.httpStatus = httpStatus;
}
当抛出异常时,我将此异常类发送到客户端。我还使用Spring-Security and JWT
进行Authentication and Authorization
进程。
当用户通过点击端点/rest/login
登录到应用程序时,如果凭据错误,则spring正在向客户端抛出异常。
如何捕获安全过滤器抛出的异常并创建用户定义的异常并将其发送到客户端?
我的过滤方式,
@Override
public Authentication attemptAuthentication( HttpServletRequest request, HttpServletResponse response )
{
try
{
UserModel credentials = new ObjectMapper().readValue(request.getInputStream(), UserModel.class);
return authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(credentials.getEmailId(),
credentials.getPassword(), new ArrayList<>()));
}
catch( IOException | AuthenticationException e )
{
LOGGER.error("Exception", "Invalid EmailId/Password");
throw new BadCredentialsException("Invalid EmailId/password");
}
}
答案 0 :(得分:0)
我从未发现从身份验证/授权过滤器中抛出异常非常有用。我只是记录错误,设置适当的响应状态&amp;消息并返回null
,因为没有必要继续下去。
AbstractAuthenticationProcessingFilter
正确处理null
。
我发现这种方法比抛出异常更清晰。然后处理那些因为通常只有一个或两个过滤器。
您可以Follow this answer使用专用过滤器来处理来自其他过滤器的异常。
您也可以使用Access Denied Handler approach。您只需设置适当的Http状态,而不是重定向到页面。