org.jboss.resteasy.annotations.cache.NoCache Java Examples

The following examples show how to use org.jboss.resteasy.annotations.cache.NoCache. 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: PolicyResourceService.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Path("/scopes")
@GET
@Produces("application/json")
@NoCache
public Response getScopes() {
    if (auth != null) {
        this.auth.realm().requireViewAuthorization();
    }

    if (policy == null) {
        return Response.status(Status.NOT_FOUND).build();
    }

    return Response.ok(policy.getScopes().stream().map(scope -> {
        ScopeRepresentation representation = new ScopeRepresentation();

        representation.setId(scope.getId());
        representation.setName(scope.getName());

        return representation;
    }).collect(Collectors.toList())).build();
}
 
Example #2
Source File: ClientAttributeCertificateResource.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Generate a new certificate with new key pair
 *
 * @return
 */
@POST
@NoCache
@Path("generate")
@Produces(MediaType.APPLICATION_JSON)
public CertificateRepresentation generate() {
    auth.clients().requireConfigure(client);

    CertificateRepresentation info = KeycloakModelUtils.generateKeyPairCertificate(client.getClientId());

    CertificateInfoHelper.updateClientModelCertificateInfo(client, info, attributePrefix);

    adminEvent.operation(OperationType.ACTION).resourcePath(session.getContext().getUri()).representation(info).success();

    return info;
}
 
Example #3
Source File: PolicyService.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Path("/search")
@GET
@Produces(MediaType.APPLICATION_JSON)
@NoCache
public Response findByName(@QueryParam("name") String name, @QueryParam("fields") String fields) {
    if (auth != null) {
        this.auth.realm().requireViewAuthorization();
    }

    StoreFactory storeFactory = authorization.getStoreFactory();

    if (name == null) {
        return Response.status(Status.BAD_REQUEST).build();
    }

    Policy model = storeFactory.getPolicyStore().findByName(name, this.resourceServer.getId());

    if (model == null) {
        return Response.noContent().build();
    }

    return Response.ok(toRepresentation(model, fields, authorization)).build();
}
 
Example #4
Source File: ValidateEndpoint.java    From keycloak-protocol-cas with Apache License 2.0 6 votes vote down vote up
@GET
@NoCache
public Response build() {
    MultivaluedMap<String, String> params = session.getContext().getUri().getQueryParameters();
    String service = params.getFirst(CASLoginProtocol.SERVICE_PARAM);
    String ticket = params.getFirst(CASLoginProtocol.TICKET_PARAM);
    boolean renew = params.containsKey(CASLoginProtocol.RENEW_PARAM);

    event.event(EventType.CODE_TO_TOKEN);

    try {
        checkSsl();
        checkRealm();
        checkClient(service);

        checkTicket(ticket, renew);

        event.success();
        return successResponse();
    } catch (CASValidationException e) {
        return errorResponse(e);
    }
}
 
Example #5
Source File: ClientRegistrationPolicyResource.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Base path for retrieve providers with the configProperties properly filled
 *
 * @return
 */
@Path("providers")
@GET
@NoCache
@Produces(MediaType.APPLICATION_JSON)
public List<ComponentTypeRepresentation> getProviders() {
    List<ProviderFactory> providerFactories = session.getKeycloakSessionFactory().getProviderFactories(ClientRegistrationPolicy.class);

    return providerFactories.stream().map((ProviderFactory factory) -> {

        ClientRegistrationPolicyFactory clientRegFactory = (ClientRegistrationPolicyFactory) factory;
        List<ProviderConfigProperty> configProps = clientRegFactory.getConfigProperties(session);

        ComponentTypeRepresentation rep = new ComponentTypeRepresentation();
        rep.setId(clientRegFactory.getId());
        rep.setHelpText(clientRegFactory.getHelpText());
        rep.setProperties(ModelToRepresentation.toRepresentation(configProps));
        return rep;

    }).collect(Collectors.toList());
}
 
Example #6
Source File: ClientResource.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Get user sessions for client
 *
 * Returns a list of user sessions associated with this client
 *
 * @param firstResult Paging offset
 * @param maxResults Maximum results size (defaults to 100)
 * @return
 */
@Path("user-sessions")
@GET
@NoCache
@Produces(MediaType.APPLICATION_JSON)
public List<UserSessionRepresentation> getUserSessions(@QueryParam("first") Integer firstResult, @QueryParam("max") Integer maxResults) {
    auth.clients().requireView(client);

    firstResult = firstResult != null ? firstResult : -1;
    maxResults = maxResults != null ? maxResults : Constants.DEFAULT_MAX_RESULTS;
    List<UserSessionRepresentation> sessions = new ArrayList<UserSessionRepresentation>();
    for (UserSessionModel userSession : session.sessions().getUserSessions(client.getRealm(), client, firstResult, maxResults)) {
        UserSessionRepresentation rep = ModelToRepresentation.toRepresentation(userSession);
        sessions.add(rep);
    }
    return sessions;
}
 
Example #7
Source File: ClientStorageProviderResource.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Need this for admin console to display simple name of provider when displaying client detail
 *
 * KEYCLOAK-4328
 *
 * @param id
 * @return
 */
@GET
@Path("{id}/name")
@NoCache
@Produces(MediaType.APPLICATION_JSON)
public Map<String, String> getSimpleName(@PathParam("id") String id) {
    auth.clients().requireList();

    ComponentModel model = realm.getComponent(id);
    if (model == null) {
        throw new NotFoundException("Could not find component");
    }
    if (!model.getProviderType().equals(ClientStorageProvider.class.getName())) {
        throw new NotFoundException("found, but not a ClientStorageProvider");
    }

    Map<String, String> data = new HashMap<>();
    data.put("id", model.getId());
    data.put("name", model.getName());
    return data;
}
 
Example #8
Source File: ScopeMappedResource.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Get realm-level roles associated with the client's scope
 *
 * @return
 */
@Path("realm")
@GET
@Produces(MediaType.APPLICATION_JSON)
@NoCache
public List<RoleRepresentation> getRealmScopeMappings() {
    viewPermission.require();

    if (scopeContainer == null) {
        throw new NotFoundException("Could not find client");
    }

    Set<RoleModel> realmMappings = scopeContainer.getRealmScopeMappings();
    List<RoleRepresentation> realmMappingsRep = new ArrayList<RoleRepresentation>();
    for (RoleModel roleModel : realmMappings) {
        realmMappingsRep.add(ModelToRepresentation.toBriefRepresentation(roleModel));
    }
    return realmMappingsRep;
}
 
Example #9
Source File: ClientRoleMappingsResource.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Get effective client-level role mappings
 *
 * This recurses any composite roles
 *
 * @return
 */
@Path("composite")
@GET
@Produces(MediaType.APPLICATION_JSON)
@NoCache
public List<RoleRepresentation> getCompositeClientRoleMappings() {
    viewPermission.require();


    Set<RoleModel> roles = client.getRoles();
    List<RoleRepresentation> mapRep = new ArrayList<RoleRepresentation>();
    for (RoleModel roleModel : roles) {
        if (user.hasRole(roleModel)) mapRep.add(ModelToRepresentation.toBriefRepresentation(roleModel));
    }
    return mapRep;
}
 
Example #10
Source File: UserStorageProviderResource.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Unlink imported users from a storage provider
 *
 *
 * @param id
 * @return
 */
@POST
@Path("{id}/unlink-users")
@NoCache
public void unlinkUsers(@PathParam("id") String id) {
    auth.users().requireManage();

    ComponentModel model = realm.getComponent(id);
    if (model == null) {
        throw new NotFoundException("Could not find component");
    }
    if (!model.getProviderType().equals(UserStorageProvider.class.getName())) {
        throw new NotFoundException("found, but not a UserStorageProvider");
    }

    session.users().unlinkUsers(realm, id);
}
 
Example #11
Source File: GroupResource.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Return object stating whether client Authorization permissions have been initialized or not and a reference
 *
 *
 * @return initialized manage permissions reference
 */
@Path("management/permissions")
@PUT
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@NoCache
public ManagementPermissionReference setManagementPermissionsEnabled(ManagementPermissionReference ref) {
    auth.groups().requireManage(group);
    AdminPermissionManagement permissions = AdminPermissions.management(session, realm);
    permissions.groups().setPermissionsEnabled(group, ref.isEnabled());
    if (ref.isEnabled()) {
        return toMgmtRef(group, permissions);
    } else {
        return new ManagementPermissionReference();
    }
}
 
Example #12
Source File: UserResource.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Revoke consent and offline tokens for particular client from user
 *
 * @param clientId Client id
 */
@Path("consents/{client}")
@DELETE
@NoCache
public void revokeConsent(final @PathParam("client") String clientId) {
    auth.users().requireManage(user);

    ClientModel client = realm.getClientByClientId(clientId);
    if (client == null) {
        throw new NotFoundException("Client not found");
    }
    boolean revokedConsent = session.users().revokeConsentForClient(realm, user.getId(), client.getId());
    boolean revokedOfflineToken = new UserSessionManager(session).revokeOfflineToken(user, client);

    if (revokedConsent) {
        // Logout clientSessions for this user and client
        AuthenticationManager.backchannelLogoutUserFromClient(session, realm, user, client, session.getContext().getUri(), headers);
    }

    if (!revokedConsent && !revokedOfflineToken) {
        throw new NotFoundException("Consent nor offline token not found");
    }
    adminEvent.operation(OperationType.ACTION).resourcePath(session.getContext().getUri()).success();
}
 
Example #13
Source File: ProtocolMappersResource.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Update the mapper
 *
 * @param id Mapper id
 * @param rep
 */
@PUT
@NoCache
@Path("models/{id}")
@Consumes(MediaType.APPLICATION_JSON)
public void update(@PathParam("id") String id, ProtocolMapperRepresentation rep) {
    managePermission.require();

    ProtocolMapperModel model = client.getProtocolMapperById(id);
    if (model == null) throw new NotFoundException("Model not found");
    model = RepresentationToModel.toModel(rep);

    validateModel(model);

    client.updateProtocolMapper(model);
    adminEvent.operation(OperationType.UPDATE).resourcePath(session.getContext().getUri()).representation(rep).success();
}
 
Example #14
Source File: ProtocolMappersResource.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Get mappers
 *
 * @return
 */
@GET
@NoCache
@Path("models")
@Produces(MediaType.APPLICATION_JSON)
public List<ProtocolMapperRepresentation> getMappers() {
    viewPermission.require();

    List<ProtocolMapperRepresentation> mappers = new LinkedList<ProtocolMapperRepresentation>();
    for (ProtocolMapperModel mapper : client.getProtocolMappers()) {
        if (isEnabled(session, mapper)) {
            mappers.add(ModelToRepresentation.toRepresentation(mapper));
        }
    }
    return mappers;
}
 
Example #15
Source File: ResourceSetService.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@Path("/search")
@GET
@NoCache
@Produces("application/json")
public Response find(@QueryParam("name") String name) {
    this.auth.realm().requireViewAuthorization();
    StoreFactory storeFactory = authorization.getStoreFactory();

    if (name == null) {
        return Response.status(Status.BAD_REQUEST).build();
    }

    Resource model = storeFactory.getResourceStore().findByName(name, this.resourceServer.getId());

    if (model == null) {
        return Response.status(Status.NO_CONTENT).build();
    }

    return Response.ok(toRepresentation(model, this.resourceServer, authorization)).build();
}
 
Example #16
Source File: AuthenticationManagementResource.java    From keycloak with Apache License 2.0 6 votes vote down vote up
/**
 * Get Single Execution
 */
@Path("/executions/{executionId}")
@GET
@NoCache
@Produces(MediaType.APPLICATION_JSON)
public Response getExecution(final @PathParam("executionId") String executionId) {
	//http://localhost:8080/auth/admin/realms/master/authentication/executions/cf26211b-9e68-4788-b754-1afd02e59d7f
    auth.realm().requireManageRealm();

    final Optional<AuthenticationExecutionModel> model = Optional.ofNullable(realm.getAuthenticationExecutionById(executionId));
    if (!model.isPresent()) {
        logger.debugv("Could not find execution by Id: {}", executionId);
        throw new NotFoundException("Illegal execution");
    }

    return Response.ok(model.get()).build();
}
 
Example #17
Source File: UserResource.java    From keycloak with Apache License 2.0 6 votes vote down vote up
@GET
@NoCache
@Path("groups/count")
@Produces(MediaType.APPLICATION_JSON)
public Map<String, Long> getGroupMembershipCount(@QueryParam("search") String search) {
    auth.users().requireView(user);
    Long results;

    if (Objects.nonNull(search)) {
        results = user.getGroupsCountByNameContaining(search);
    } else {
        results = user.getGroupsCount();
    }
    Map<String, Long> map = new HashMap<>();
    map.put("count", results);
    return map;
}
 
Example #18
Source File: RealmResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Path("events")
@GET
@NoCache
@Produces(MediaType.APPLICATION_JSON)
List<EventRepresentation> getEvents(@QueryParam("type") List<String> types, @QueryParam("client") String client,
        @QueryParam("user") String user, @QueryParam("dateFrom") String dateFrom, @QueryParam("dateTo") String dateTo,
        @QueryParam("ipAddress") String ipAddress, @QueryParam("first") Integer firstResult,
        @QueryParam("max") Integer maxResults);
 
Example #19
Source File: ProductService.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@GET
@Produces("application/json")
@NoCache
public List<String> getProducts() {
    ArrayList<String> rtn = new ArrayList<String>();
    rtn.add("iphone");
    rtn.add("ipad");
    rtn.add("ipod");
    return rtn;
}
 
Example #20
Source File: IdentityProvidersResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Get identity providers
 *
 * @return
 */
@GET
@Path("instances")
@NoCache
@Produces(MediaType.APPLICATION_JSON)
public List<IdentityProviderRepresentation> getIdentityProviders() {
    this.auth.realm().requireViewIdentityProviders();

    List<IdentityProviderRepresentation> representations = new ArrayList<IdentityProviderRepresentation>();

    for (IdentityProviderModel identityProviderModel : realm.getIdentityProviders()) {
        representations.add(StripSecretsUtils.strip(ModelToRepresentation.toRepresentation(realm, identityProviderModel)));
    }
    return representations;
}
 
Example #21
Source File: AccountRestService.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * CORS preflight
 *
 * @return
 */
@Path("/")
@OPTIONS
@NoCache
public Response preflight() {
    return Cors.add(request, Response.ok()).auth().preflight().build();
}
 
Example #22
Source File: AccountCredentialResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Remove a credential of current user
 *
 * @param credentialId ID of the credential, which will be removed
 */
@Path("{credentialId}")
@DELETE
@NoCache
public void removeCredential(final @PathParam("credentialId") String credentialId) {
    auth.require(AccountRoles.MANAGE_ACCOUNT);
    CredentialModel credential = session.userCredentialManager().getStoredCredentialById(realm, user, credentialId);
    if (credential == null) {
        throw new NotFoundException("Credential not found");
    }
    session.userCredentialManager().removeStoredCredential(realm, user, credentialId);
}
 
Example #23
Source File: UserStorageProviderResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Trigger sync of mapper data related to ldap mapper (roles, groups, ...)
 *
 * direction is "fedToKeycloak" or "keycloakToFed"
 *
 * @return
 */
@POST
@Path("{parentId}/mappers/{id}/sync")
@NoCache
@Produces(MediaType.APPLICATION_JSON)
public SynchronizationResult syncMapperData(@PathParam("parentId") String parentId, @PathParam("id") String mapperId, @QueryParam("direction") String direction) {
    auth.users().requireManage();

    ComponentModel parentModel = realm.getComponent(parentId);
    if (parentModel == null) throw new NotFoundException("Parent model not found");
    ComponentModel mapperModel = realm.getComponent(mapperId);
    if (mapperModel == null) throw new NotFoundException("Mapper model not found");

    LDAPStorageProvider ldapProvider = (LDAPStorageProvider) session.getProvider(UserStorageProvider.class, parentModel);
    LDAPStorageMapper mapper = session.getProvider(LDAPStorageMapper.class, mapperModel);

    ServicesLogger.LOGGER.syncingDataForMapper(mapperModel.getName(), mapperModel.getProviderId(), direction);

    SynchronizationResult syncResult;
    if ("fedToKeycloak".equals(direction)) {
        syncResult = mapper.syncDataFromFederationProviderToKeycloak(realm);
    } else if ("keycloakToFed".equals(direction)) {
        syncResult = mapper.syncDataFromKeycloakToFederationProvider(realm);
    } else {
        throw new BadRequestException("Unknown direction: " + direction);
    }

    Map<String, Object> eventRep = new HashMap<>();
    eventRep.put("action", direction);
    eventRep.put("result", syncResult);
    adminEvent.operation(OperationType.ACTION).resourcePath(session.getContext().getUri()).representation(eventRep).success();
    return syncResult;
}
 
Example #24
Source File: ClientScopeEvaluateResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Create JSON with payload of example access token
 *
 * @return
 */
@GET
@Path("generate-example-access-token")
@NoCache
@Produces(MediaType.APPLICATION_JSON)
public AccessToken generateExampleAccessToken(@QueryParam("scope") String scopeParam, @QueryParam("userId") String userId) {
    auth.clients().requireView(client);

    if (userId == null) {
        throw new NotFoundException("No userId provided");
    }

    UserModel user = session.users().getUserById(userId, realm);
    if (user == null) {
        throw new NotFoundException("No user found");
    }

    logger.debugf("generateExampleAccessToken invoked. User: %s, Scope param: %s", user.getUsername(), scopeParam);

    AccessToken token = generateToken(user, scopeParam);
    return token;
}
 
Example #25
Source File: AuthenticationManagementResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Lower required action's priority
 *
 * @param alias Alias of required action
 */
@Path("/required-actions/{alias}/lower-priority")
@POST
@NoCache
public void lowerRequiredActionPriority(@PathParam("alias") String alias) {
    auth.realm().requireManageRealm();

    RequiredActionProviderModel model = realm.getRequiredActionProviderByAlias(alias);
    if (model == null) {
        throw new NotFoundException("Failed to find required action.");
    }

    List<RequiredActionProviderModel> actions = realm.getRequiredActionProviders();
    int i = 0;
    for (i = 0; i < actions.size(); i++) {
        if (actions.get(i).getId().equals(model.getId())) {
            break;
        }
    }
    if (i + 1 >= actions.size()) return;
    RequiredActionProviderModel next = actions.get(i + 1);
    int tmp = model.getPriority();
    model.setPriority(next.getPriority());
    realm.updateRequiredActionProvider(model);
    next.setPriority(tmp);
    realm.updateRequiredActionProvider(next);

    adminEvent.operation(OperationType.UPDATE).resource(ResourceType.REQUIRED_ACTION).resourcePath(session.getContext().getUri()).success();
}
 
Example #26
Source File: GroupsResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Get groups by pagination params.
 * @param search max number of occurrences
 * @param first index of the first element
 * @param max max number of occurrences
 * @param briefRepresentation if false, return groups with their attributes
 * @return A list containing the slice of all groups.
 */
@GET
@NoCache
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
List<GroupRepresentation> groups(@QueryParam("search") String search,
                                 @QueryParam("first") Integer first,
                                 @QueryParam("max") Integer max,
                                 @QueryParam("briefRepresentation") @DefaultValue("true") boolean briefRepresentation);
 
Example #27
Source File: SessionResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Get session information.
 *
 * @return
 */
@GET
@Produces(MediaType.APPLICATION_JSON)
@NoCache
public Response toRepresentation() {
    return Cors.add(request, Response.ok(session.sessions().getUserSessions(realm, user).stream()
            .map(this::toRepresentation).collect(Collectors.toList()))).auth().allowedOrigins(auth.getToken()).build();
}
 
Example #28
Source File: ClientAttributeCertificateResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Get a keystore file for the client, containing private key and public certificate
 *
 * @param config Keystore configuration as JSON
 * @return
 */
@POST
@NoCache
@Path("/download")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
@Consumes(MediaType.APPLICATION_JSON)
byte[] getKeystore(final KeyStoreConfig config);
 
Example #29
Source File: AdminConsole.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Adapter configuration for the admin console for this realm
 *
 * @return
 */
@Path("config")
@GET
@Produces(MediaType.APPLICATION_JSON)
@NoCache
public ClientManager.InstallationAdapterConfig config() {
    ClientModel consoleApp = realm.getClientByClientId(Constants.ADMIN_CONSOLE_CLIENT_ID);
    if (consoleApp == null) {
        throw new NotFoundException("Could not find admin console client");
    }
    return new ClientManager(new RealmManager(session)).toInstallationRepresentation(realm, consoleApp, session.getContext().getUri().getBaseUri());    }
 
Example #30
Source File: AuthenticationManagementResource.java    From keycloak with Apache License 2.0 5 votes vote down vote up
/**
 * Delete execution
 *
 * @param execution Execution id
 */
@Path("/executions/{executionId}")
@DELETE
@NoCache
public void removeExecution(@PathParam("executionId") String execution) {
    auth.realm().requireManageRealm();

    AuthenticationExecutionModel model = realm.getAuthenticationExecutionById(execution);
    if (model == null) {
        session.getTransactionManager().setRollbackOnly();
        throw new NotFoundException("Illegal execution");

    }
    AuthenticationFlowModel parentFlow = getParentFlow(model);
    if (parentFlow.isBuiltIn()) {
        throw new BadRequestException("It is illegal to remove execution from a built in flow");
    }

    if(model.getFlowId() != null) {
    	AuthenticationFlowModel nonTopLevelFlow = realm.getAuthenticationFlowById(model.getFlowId());
    	realm.removeAuthenticationFlow(nonTopLevelFlow);
    }

    realm.removeAuthenticatorExecution(model);

    adminEvent.operation(OperationType.DELETE).resource(ResourceType.AUTH_EXECUTION).resourcePath(session.getContext().getUri()).success();
}