thomasdarimont / keycloak-extension-playground

Simple project environment for creating custom Keycloak extensions
Apache License 2.0
659 stars 170 forks source link

Auth Require Role Extension not working with direct grant flow #10

Closed chris-rl closed 4 years ago

chris-rl commented 4 years ago

Hello, I'm trying to use your 'auth require role'-extension to add the require-role check to a direct-grant-flow. When the user owns the required role, the flow returns the correct token.

But if the user doesn't own the required role, I'm getting a 500 from the token endpoint. I would like to get a 401.

As far as I understand, the extension is meant to be used for browser-flows. Can this be updated for usage with direct grant flow?

What would I need to put in the authenticate()-Method for the case the role ist missing?

@Override
public void authenticate(AuthenticationFlowContext context) {

    AuthenticatorConfigModel configModel = context.getAuthenticatorConfig();

    String roleName = configModel.getConfig().get(RequireRoleAuthenticatorFactory.ROLE);
    RealmModel realm = context.getRealm();
    UserModel user = context.getUser();

    if (userHasRole(realm, user, roleName)) {
        context.success();
        return;
    }

    LOG.debugf("Access denied because of missing role. realm=%s username=%s role=%s", realm.getName(), user.getUsername(), roleName);
    context.getEvent().user(user);
    context.getEvent().error(Errors.NOT_ALLOWED);

    // the following doesn't work for direct-grant-flow: it returns a 500
    context.forkWithErrorMessage(new FormMessage(Messages.NO_ACCESS));
}

Kind Regards, Christian

chris-rl commented 4 years ago

I solved it. I introduced a new (derived) authenticator which can be used for direct-grant-flows. You can find a PR for this change here https://github.com/thomasdarimont/keycloak-extension-playground/pull/11

Greetings.

thomasdarimont commented 4 years ago

Fixed with merging #11