Java Code Examples for org.keycloak.models.ClientModel#isPublicClient()

The following examples show how to use org.keycloak.models.ClientModel#isPublicClient() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TokenIntrospectionEndpoint.java    From keycloak with Apache License 2.0 6 votes vote down vote up
private void authorizeClient() {
    try {
        ClientModel client = AuthorizeClientUtil.authorizeClient(session, event).getClient();

        this.event.client(client);

        if (client == null || client.isPublicClient()) {
            throw throwErrorResponseException(Errors.INVALID_REQUEST, "Client not allowed.", Status.FORBIDDEN);
        }

    } catch (ErrorResponseException ere) {
        throw ere;
    } catch (Exception e) {
        throw throwErrorResponseException(Errors.INVALID_REQUEST, "Authentication failed.", Status.UNAUTHORIZED);
    }
}
 
Example 2
Source File: ClientManager.java    From keycloak with Apache License 2.0 6 votes vote down vote up
public InstallationAdapterConfig toInstallationRepresentation(RealmModel realmModel, ClientModel clientModel, URI baseUri) {
    InstallationAdapterConfig rep = new InstallationAdapterConfig();
    rep.setAuthServerUrl(baseUri.toString());
    rep.setRealm(realmModel.getName());
    rep.setSslRequired(realmModel.getSslRequired().name().toLowerCase());

    if (clientModel.isPublicClient() && !clientModel.isBearerOnly()) rep.setPublicClient(true);
    if (clientModel.isBearerOnly()) rep.setBearerOnly(true);
    if (clientModel.getRoles().size() > 0) rep.setUseResourceRoleMappings(true);

    rep.setResource(clientModel.getClientId());

    if (showClientCredentialsAdapterConfig(clientModel)) {
        Map<String, Object> adapterConfig = getClientCredentialsAdapterConfig(clientModel);
        rep.setCredentials(adapterConfig);
    }

    return rep;
}
 
Example 3
Source File: RepresentationToModel.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static ResourceServer createResourceServer(ClientModel client, KeycloakSession session, boolean addDefaultRoles) {
    if ((client.isBearerOnly() || client.isPublicClient())
            && !(client.getClientId().equals(Config.getAdminRealm() + "-realm") || client.getClientId().equals(Constants.REALM_MANAGEMENT_CLIENT_ID))) {
        throw new RuntimeException("Only confidential clients are allowed to set authorization settings");
    }
    AuthorizationProvider authorization = session.getProvider(AuthorizationProvider.class);
    UserModel serviceAccount = session.users().getServiceAccount(client);

    if (serviceAccount == null) {
        client.setServiceAccountsEnabled(true);
    }

    if (addDefaultRoles) {
        RoleModel umaProtectionRole = client.getRole(Constants.AUTHZ_UMA_PROTECTION);

        if (umaProtectionRole == null) {
            umaProtectionRole = client.addRole(Constants.AUTHZ_UMA_PROTECTION);
        }

        if (serviceAccount != null) {
            serviceAccount.grantRole(umaProtectionRole);
        }
    }

    ResourceServerRepresentation representation = new ResourceServerRepresentation();

    representation.setAllowRemoteResourceManagement(true);
    representation.setClientId(client.getId());

    return toModel(representation, authorization);
}
 
Example 4
Source File: KeycloakOIDCJbossSubsystemClientCliInstallation.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public Response generateInstallation(KeycloakSession session, RealmModel realm, ClientModel client, URI baseUri) {
    String deploymentName = "WAR MODULE NAME.war";
    StringBuilder builder = new StringBuilder();
    
    builder
            .append("/subsystem=keycloak/secure-deployment=").append(quote(deploymentName)).append("/:add( \\\n")
            .append("    realm=").append(quote(realm.getName())).append(", \\\n")
            .append("    resource=").append(quote(client.getClientId())).append(", \\\n")
            .append("    auth-server-url=").append(baseUri).append(", \\\n");

    if (client.isBearerOnly()){
        builder.append("    bearer-only=true, \\\n");
    } else if (client.isPublicClient()) {
        builder.append("    public-client=true, \\\n");
    }

    if (KeycloakOIDCClientInstallation.showVerifyTokenAudience(client)) {
        builder.append("    verify-token-audience=true, \\\n");
    }
    if (client.getRoles().size() > 0) {
        builder.append("    use-resource-role-mappings=true, \\\n");
    }
    builder.append("    ssl-required=").append(realm.getSslRequired().name()).append(")\n\n");


    if (KeycloakOIDCClientInstallation.showClientCredentialsAdapterConfig(client)) {
        Map<String, Object> adapterConfig = KeycloakOIDCClientInstallation.getClientCredentialsAdapterConfig(session, client);
        for (Map.Entry<String, Object> entry : adapterConfig.entrySet()) {
            builder.append("/subsystem=keycloak/secure-deployment=").append(quote(deploymentName)).append("/")
                   .append("credential=").append(entry.getKey()).append(":add(value=").append(entry.getValue())
                   .append(")\n");
        }
    }
    return Response.ok(builder.toString(), MediaType.TEXT_PLAIN_TYPE).build();
}
 
Example 5
Source File: KeycloakOIDCClientInstallation.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
public Response generateInstallation(KeycloakSession session, RealmModel realm, ClientModel client, URI baseUri) {
    ClientManager.InstallationAdapterConfig rep = new ClientManager.InstallationAdapterConfig();
    rep.setAuthServerUrl(baseUri.toString());
    rep.setRealm(realm.getName());
    rep.setSslRequired(realm.getSslRequired().name().toLowerCase());

    if (client.isPublicClient() && !client.isBearerOnly()) rep.setPublicClient(true);
    if (client.isBearerOnly()) rep.setBearerOnly(true);
    if (client.getRoles().size() > 0) rep.setUseResourceRoleMappings(true);

    rep.setResource(client.getClientId());

    if (showClientCredentialsAdapterConfig(client)) {
        Map<String, Object> adapterConfig = getClientCredentialsAdapterConfig(session, client);
        rep.setCredentials(adapterConfig);
    }

    if (showVerifyTokenAudience(client)) {
        rep.setVerifyTokenAudience(true);
    }

    configureAuthorizationSettings(session, client, rep);

    String json = null;
    try {
        json = JsonSerialization.writeValueAsPrettyString(rep);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return Response.ok(json, MediaType.TEXT_PLAIN_TYPE).build();
}
 
Example 6
Source File: KeycloakOIDCClientInstallation.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public static boolean showClientCredentialsAdapterConfig(ClientModel client) {
    if (client.isPublicClient()) {
        return false;
    }

    if (client.isBearerOnly() && !client.isServiceAccountsEnabled() && client.getNodeReRegistrationTimeout() <= 0) {
        return false;
    }

    return true;
}
 
Example 7
Source File: OpenShiftTokenReviewEndpoint.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private void authorizeClient() {
    try {
        ClientModel client = AuthorizeClientUtil.authorizeClient(session, event).getClient();
        event.client(client);

        if (client == null || client.isPublicClient()) {
            error(401, Errors.INVALID_CLIENT, "Public client is not permitted to invoke token review endpoint");
        }

    } catch (ErrorResponseException ere) {
        error(401, Errors.INVALID_CLIENT_CREDENTIALS, ere.getErrorDescription());
    } catch (Exception e) {
        error(401, Errors.INVALID_CLIENT_CREDENTIALS, null);
    }
}
 
Example 8
Source File: ClientsManagementService.java    From keycloak with Apache License 2.0 5 votes vote down vote up
protected ClientModel authorizeClient() {
    ClientModel client = AuthorizeClientUtil.authorizeClient(session, event).getClient();

    if (client.isPublicClient()) {
        OAuth2ErrorRepresentation errorRep = new OAuth2ErrorRepresentation(OAuthErrorException.INVALID_CLIENT, "Public clients not allowed");
        event.error(Errors.INVALID_CLIENT);
        throw new BadRequestException("Public clients not allowed", javax.ws.rs.core.Response.status(javax.ws.rs.core.Response.Status.BAD_REQUEST).entity(errorRep).type(MediaType.APPLICATION_JSON_TYPE).build());
    }

    return client;
}
 
Example 9
Source File: ClientManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
public String toJBossSubsystemConfig(RealmModel realmModel, ClientModel clientModel, URI baseUri) {
    StringBuffer buffer = new StringBuffer();
    buffer.append("<secure-deployment name=\"WAR MODULE NAME.war\">\n");
    buffer.append("    <realm>").append(realmModel.getName()).append("</realm>\n");
    buffer.append("    <auth-server-url>").append(baseUri.toString()).append("</auth-server-url>\n");
    if (clientModel.isBearerOnly()){
        buffer.append("    <bearer-only>true</bearer-only>\n");

    } else if (clientModel.isPublicClient()) {
        buffer.append("    <public-client>true</public-client>\n");
    }
    buffer.append("    <ssl-required>").append(realmModel.getSslRequired().name()).append("</ssl-required>\n");
    buffer.append("    <resource>").append(clientModel.getClientId()).append("</resource>\n");
    String cred = clientModel.getSecret();
    if (showClientCredentialsAdapterConfig(clientModel)) {
        Map<String, Object> adapterConfig = getClientCredentialsAdapterConfig(clientModel);
        for (Map.Entry<String, Object> entry : adapterConfig.entrySet()) {
            buffer.append("    <credential name=\"" + entry.getKey() + "\">");

            Object value = entry.getValue();
            if (value instanceof Map) {
                buffer.append("\n");
                Map<String, Object> asMap = (Map<String, Object>) value;
                for (Map.Entry<String, Object> credEntry : asMap.entrySet()) {
                    buffer.append("        <" + credEntry.getKey() + ">" + credEntry.getValue().toString() + "</" + credEntry.getKey() + ">\n");
                }
                buffer.append("    </credential>\n");
            } else {
                buffer.append(value.toString()).append("</credential>\n");
            }
        }
    }
    if (clientModel.getRoles().size() > 0) {
        buffer.append("    <use-resource-role-mappings>true</use-resource-role-mappings>\n");
    }
    buffer.append("</secure-deployment>\n");
    return buffer.toString();
}
 
Example 10
Source File: ClientManager.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private boolean showClientCredentialsAdapterConfig(ClientModel client) {
    if (client.isPublicClient()) {
        return false;
    }

    if (client.isBearerOnly() && client.getNodeReRegistrationTimeout() <= 0) {
        return false;
    }

    return true;
}
 
Example 11
Source File: ClientRegistrationAuth.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private boolean authenticateClient(ClientModel client) {
    if (client == null) {
        return false;
    }

    if (client.isPublicClient()) {
        return true;
    }

    AuthenticationProcessor processor = AuthorizeClientUtil.getAuthenticationProcessor(session, event);

    Response response = processor.authenticateClient();
    if (response != null) {
        event.client(client.getClientId()).error(Errors.NOT_ALLOWED);
        throw unauthorized("Failed to authenticate client");
    }

    ClientModel authClient = processor.getClient();
    if (authClient == null) {
        event.client(client.getClientId()).error(Errors.NOT_ALLOWED);
        throw unauthorized("No client authenticated");
    }

    if (!authClient.getClientId().equals(client.getClientId())) {
        event.client(client.getClientId()).error(Errors.NOT_ALLOWED);
        throw unauthorized("Different client authenticated");
    }

    checkClientProtocol(authClient);

    return true;
}
 
Example 12
Source File: KeycloakOIDCJbossSubsystemClientInstallation.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
public Response generateInstallation(KeycloakSession session, RealmModel realm, ClientModel client, URI baseUri) {
    StringBuffer buffer = new StringBuffer();
    buffer.append("<secure-deployment name=\"WAR MODULE NAME.war\">\n");
    buffer.append("    <realm>").append(realm.getName()).append("</realm>\n");
    buffer.append("    <auth-server-url>").append(baseUri.toString()).append("</auth-server-url>\n");
    if (client.isBearerOnly()){
        buffer.append("    <bearer-only>true</bearer-only>\n");

    } else if (client.isPublicClient()) {
        buffer.append("    <public-client>true</public-client>\n");
    }
    buffer.append("    <ssl-required>").append(realm.getSslRequired().name()).append("</ssl-required>\n");
    buffer.append("    <resource>").append(client.getClientId()).append("</resource>\n");

    if (KeycloakOIDCClientInstallation.showVerifyTokenAudience(client)) {
        buffer.append("    <verify-token-audience>true</verify-token-audience>\n");
    }

    String cred = client.getSecret();
    if (KeycloakOIDCClientInstallation.showClientCredentialsAdapterConfig(client)) {
        Map<String, Object> adapterConfig = KeycloakOIDCClientInstallation.getClientCredentialsAdapterConfig(session, client);
        for (Map.Entry<String, Object> entry : adapterConfig.entrySet()) {
            buffer.append("    <credential name=\"" + entry.getKey() + "\">");

            Object value = entry.getValue();
            if (value instanceof Map) {
                buffer.append("\n");
                Map<String, Object> asMap = (Map<String, Object>) value;
                for (Map.Entry<String, Object> credEntry : asMap.entrySet()) {
                    buffer.append("        <" + credEntry.getKey() + ">" + credEntry.getValue().toString() + "</" + credEntry.getKey() + ">\n");
                }
                buffer.append("    </credential>\n");
            } else {
                buffer.append(value.toString()).append("</credential>\n");
            }
        }
    }
    if (client.getRoles().size() > 0) {
        buffer.append("    <use-resource-role-mappings>true</use-resource-role-mappings>\n");
    }
    buffer.append("</secure-deployment>\n");
    return Response.ok(buffer.toString(), MediaType.TEXT_PLAIN_TYPE).build();
}