从Spring-Security过滤器中抛出用户定义的异常

问题描述 投票:0回答:1

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

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个回答
0
投票

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

AbstractAuthenticationProcessingFilter恰当地处理了null

我发现这种方法比抛出异常然后处理那些更清晰,因为通常只有一个或两个过滤器。

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

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

© www.soinside.com 2019 - 2024. All rights reserved.