Keycloak Script base authenticator same error message on failure

Need to send a custom error message in keycloak script based authenticator. On failure it showing same error message Incorrect email or password. Please check and try again. How to send a custom error message?

Code:

function authenticate(context) {
var username = user ? user.username : "anonymous";
var authShouldFail = false;
if (username=="anonymous") {
    context.failure(AuthenticationFlowError.INVALID_CLIENT_CREDENTIALS);
    return;
}
context.success();
}

Upvotes: 3

Views: 1255

Answers (1)

Ahmet Emre Kilinc
Ahmet Emre Kilinc

Reputation: 6905

I searched source code of keycloak repository and finally came up with a solution. The answer is to use setError method to show custom error messages and use context.failureChallenge function instead of context.failure like the following code:

// import the required Java classes
AuthenticationFlowError = Java.type("org.keycloak.authentication.AuthenticationFlowError");
Response = Java.type("javax.ws.rs.core.Response");
Errors = Java.type("org.keycloak.events.Errors");

function authenticate(context) {

    var showCustomError = true; // you need to make your own controls to set this property

    if (showCustomError) {
        var errorMessage = "this is custom error message"; // set your custom error message
        context.getEvent().error(Errors.IDENTITY_PROVIDER_ERROR);

        var challengeResponse = context.form().setError(errorMessage, []).createErrorPage(Response.Status.INTERNAL_SERVER_ERROR);

        context.failureChallenge(AuthenticationFlowError.IDENTITY_PROVIDER_ERROR, challengeResponse);
        return;
    }

    context.success();
}

Upvotes: 1

Related Questions