![](/img/trans.png)
[英]In Spring-boot, which will execute first among HandlerInterceptor, user-defined filters, and spring-security filters?
[英]Throwing user defined exceptions from Spring-Security filter
我创建了一个自定义异常类
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");
}
}
我从未发现从身份验证/授权过滤器抛出异常非常有用。 我只是记录错误,设置适当的响应状态和消息,并返回null
因为没有任何进一步的意义。
AbstractAuthenticationProcessingFilter
处理适当地将其null
。
我发现这种方法比抛出异常然后处理异常更干净,因为通常只有一两个过滤器。
您可能会遵循此答案以拥有专用的过滤器来处理其他过滤器的异常。
您也可以使用“ 访问拒绝处理程序”方法 。 无需重定向到页面,只需设置适当的Http状态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.