【问题标题】:Throwing user defined exceptions from Spring-Security filter从 Spring-Security 过滤器中抛出用户定义的异常
【发布时间】:2018-06-04 20:43:00
【问题描述】:

我创建了一个自定义异常类

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");
    }
}

【问题讨论】:

    标签: java spring-boot spring-security jwt


    【解决方案1】:

    我从未发现从身份验证/授权过滤器中抛出异常非常有用。我只是记录错误,设置适当的响应状态和消息并返回null,因为没有必要再进一步了。

    AbstractAuthenticationProcessingFilter 适当地处理 null

    我发现这种方法比抛出异常然后处理它们更干净,因为通常只有一两个过滤器。

    您可以Follow this answer 拥有一个专用过滤器来处理来自其他过滤器的异常。

    您也可以使用Access Denied Handler approach。您只需设置适当的 Http 状态,而不是重定向到页面。

    【讨论】:

      猜你喜欢
      • 2017-04-20
      • 2021-08-09
      • 2021-03-19
      • 2017-10-17
      • 2018-06-03
      • 2021-11-05
      • 2020-09-11
      • 1970-01-01
      • 2017-06-29
      相关资源
      最近更新 更多