WSO2 API 管理器 - 使用自定义验证器处理验证失败

WSO2 API Manager - Handle Authentication failure with Custom Authenticator

我正在按照本指南为 wso2-am 实施自定义身份验证处理程序 https://docs.wso2.com/display/AM190/Writing+Custom+Handlers 但是,当我的身份验证处理程序 returns 为 false 时,如何处理这种情况尚不清楚。 handleRequest 的示例代码是

public boolean handleRequest(MessageContext messageContext) {
    try {
        if (authenticate(messageContext)) {
            return true;
        }
    } catch (APISecurityException e) {
        e.printStackTrace();
    }
    return false;
}

如果我尝试使用有效凭据调用 API 一切顺利(方法 returns 为真)并且我收到 "HTTP 200 OK" 响应。如果我使用无效凭据尝试方法 returns false 但我收到 HTTP 202 ACCEPTED" 响应。我想接收另一个响应代码(例如 400)。我如何处理此身份验证失败路径?

谢谢。

理想情况下,您需要使用消息上下文调用 handleAuthFaliure 方法。

private void handleAuthFailure(MessageContext messageContext, APISecurityException e) 

当您调用该方法时,请创建 APISecurityException 对象(如下所列)并传递它。然后将从那里选择错误代码和错误消息并自动将错误发送给客户端(默认情况下我们 return 401 用于安全异常,如果已定义则发送定义的错误代码和消息)。

public class APISecurityException extends Exception {
    private int errorCode;
    public APISecurityException(int errorCode, String message) {
        super(message);
        this.errorCode = errorCode;
    }

    public APISecurityException(int errorCode, String message, Throwable cause) {
        super(message, cause);
        this.errorCode = errorCode;
    }

    public int getErrorCode() {
        return errorCode;
    }
}

希望这对你有用。

谢谢

sanjeewa.