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

The following examples show how to use org.keycloak.models.ClientModel#isBearerOnly() . 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: MigrateTo6_0_0.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected void migrateRealm(KeycloakSession session, RealmModel realm, boolean jsn) {
    MigrationProvider migrationProvider = session.getProvider(MigrationProvider.class);

    // create 'microprofile-jwt' optional client scope in the realm.
    ClientScopeModel mpJWTScope = migrationProvider.addOIDCMicroprofileJWTClientScope(realm);

    LOG.debugf("Added '%s' optional client scope", mpJWTScope.getName());

    // assign 'microprofile-jwt' optional client scope to all the OIDC clients.
    for (ClientModel client : realm.getClients()) {
        if ((client.getProtocol() == null || "openid-connect".equals(client.getProtocol())) && (!client.isBearerOnly())) {
            client.addClientScope(mpJWTScope, false);
        }
    }

    LOG.debugf("Client scope '%s' assigned to all the clients", mpJWTScope.getName());
}
 
Example 2
Source File: MigrateTo4_6_0.java    From keycloak with Apache License 2.0 6 votes vote down vote up
protected void migrateRealm(KeycloakSession session, RealmModel realm, boolean json) {
    MigrationProvider migrationProvider = session.getProvider(MigrationProvider.class);

    // Create "roles" and "web-origins" clientScopes
    ClientScopeModel rolesScope = migrationProvider.addOIDCRolesClientScope(realm);
    ClientScopeModel webOriginsScope = migrationProvider.addOIDCWebOriginsClientScope(realm);

    LOG.debugf("Added '%s' and '%s' default client scopes", rolesScope.getName(), webOriginsScope.getName());

    // Assign "roles" and "web-origins" clientScopes to all the OIDC clients
    for (ClientModel client : realm.getClients()) {
        if ((client.getProtocol()==null || "openid-connect".equals(client.getProtocol())) && (!client.isBearerOnly())) {
            client.addClientScope(rolesScope, true);
            client.addClientScope(webOriginsScope, true);
        }
    }

    LOG.debugf("Client scope '%s' assigned to all the clients", rolesScope.getName());
}
 
Example 3
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 4
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 5
Source File: LogoutEndpoint.java    From keycloak with Apache License 2.0 5 votes vote down vote up
private ClientModel authorizeClient() {
    ClientModel client = AuthorizeClientUtil.authorizeClient(session, event).getClient();

    if (client.isBearerOnly()) {
        throw new ErrorResponseException(Errors.INVALID_CLIENT, "Bearer-only not allowed", Response.Status.BAD_REQUEST);
    }

    return client;
}
 
Example 6
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 7
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 8
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 9
Source File: AccountRestService.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the applications with the given id in the specified realm.
 *
 * @param clientId client id to search for
 * @return application with the provided id
 */
@Path("/applications/{clientId}")
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getApplication(final @PathParam("clientId") String clientId) {
    checkAccountApiEnabled();
    auth.requireOneOf(AccountRoles.MANAGE_ACCOUNT, AccountRoles.VIEW_APPLICATIONS);
    ClientModel client = realm.getClientByClientId(clientId);
    if (client == null || client.isBearerOnly() || client.getBaseUrl() == null) {
        return Cors.add(request, Response.status(Response.Status.NOT_FOUND).entity("No client with clientId: " + clientId + " found.")).build();
    }

    List<String> inUseClients = new LinkedList<>();
    if(!session.sessions().getUserSessions(realm, client).isEmpty()) {
        inUseClients.add(clientId);
    }

    List<String> offlineClients = new LinkedList<>();
    if(session.sessions().getOfflineSessionsCount(realm, client) > 0) {
        offlineClients.add(clientId);
    }

    UserConsentModel consentModel = session.users().getConsentByClient(realm, user.getId(), client.getId());
    Map<String, UserConsentModel> consentModels = Collections.singletonMap(client.getClientId(), consentModel);

    return Cors.add(request, Response.ok(modelToRepresentation(client, inUseClients, offlineClients, consentModels))).build();
}
 
Example 10
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 11
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 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();
}
 
Example 13
Source File: SamlService.java    From keycloak with Apache License 2.0 4 votes vote down vote up
protected Response handleSamlRequest(String samlRequest, String relayState) {
    SAMLDocumentHolder documentHolder = extractRequestDocument(samlRequest);
    if (documentHolder == null) {
        event.event(EventType.LOGIN);
        event.error(Errors.INVALID_TOKEN);
        return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.INVALID_REQUEST);
    }

    SAML2Object samlObject = documentHolder.getSamlObject();

    if (samlObject instanceof AuthnRequestType) {
        logger.debug("** login request");
        event.event(EventType.LOGIN);
    } else if (samlObject instanceof LogoutRequestType) {
        logger.debug("** logout request");
        event.event(EventType.LOGOUT);
    } else {
        event.event(EventType.LOGIN);
        event.error(Errors.INVALID_TOKEN);
        event.detail(Details.REASON, "Unhandled SAML document type: " + (samlObject == null ? "<null>" : samlObject.getClass().getSimpleName()));
        return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.INVALID_REQUEST);
    }

    RequestAbstractType requestAbstractType = (RequestAbstractType) samlObject;
    final NameIDType issuerNameId = requestAbstractType.getIssuer();
    String issuer = requestAbstractType.getIssuer() == null ? null : issuerNameId.getValue();
    ClientModel client = realm.getClientByClientId(issuer);

    if (client == null) {
        event.client(issuer);
        event.error(Errors.CLIENT_NOT_FOUND);
        return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.UNKNOWN_LOGIN_REQUESTER);
    }

    if (!client.isEnabled()) {
        event.error(Errors.CLIENT_DISABLED);
        return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.LOGIN_REQUESTER_NOT_ENABLED);
    }
    if (client.isBearerOnly()) {
        event.error(Errors.NOT_ALLOWED);
        return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.BEARER_ONLY);
    }
    if (!client.isStandardFlowEnabled()) {
        event.error(Errors.NOT_ALLOWED);
        return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.STANDARD_FLOW_DISABLED);
    }
    if (!isClientProtocolCorrect(client)) {
        event.error(Errors.INVALID_CLIENT);
        return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, "Wrong client protocol.");
    }

    session.getContext().setClient(client);

    SamlClient samlClient = new SamlClient(client);
    try {
        if (samlClient.requiresClientSignature()) {
            verifySignature(documentHolder, client);
        }
    } catch (VerificationException e) {
        SamlService.logger.error("request validation failed", e);
        event.error(Errors.INVALID_SIGNATURE);
        return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.INVALID_REQUESTER);
    }
    logger.debug("verified request");

    if (requestAbstractType.getDestination() == null && containsUnencryptedSignature(documentHolder)) {
        event.detail(Details.REASON, "missing_required_destination");
        event.error(Errors.INVALID_REQUEST);
        return ErrorPage.error(session, null, Response.Status.BAD_REQUEST, Messages.INVALID_REQUEST);
    }

    if (samlObject instanceof AuthnRequestType) {
        // Get the SAML Request Message
        AuthnRequestType authn = (AuthnRequestType) samlObject;
        return loginRequest(relayState, authn, client);
    } else if (samlObject instanceof LogoutRequestType) {
        LogoutRequestType logout = (LogoutRequestType) samlObject;
        return logoutRequest(logout, client, relayState);
    } else {
        throw new IllegalStateException("Invalid SAML object");
    }
}