/** * Does resource exist? * * @param resource the resource * @param resourceLoader the resource loader * @return the boolean */ public static boolean doesResourceExist(final String resource, final ResourceLoader resourceLoader) { try { if (StringUtils.isNotBlank(resource)) { val res = resourceLoader.getResource(resource); return doesResourceExist(res); } } catch (final Exception e) { LOGGER.warn(e.getMessage(), e); } return false; }
@SneakyThrows private static Map<String, String> getDevicesFromJsonResource(final Resource jsonResource) { if (!ResourceUtils.doesResourceExist(jsonResource)) { val res = jsonResource.getFile().createNewFile(); if (res) { LOGGER.debug("Created JSON resource @ [{}]", jsonResource); } } if (ResourceUtils.doesResourceExist(jsonResource)) { val file = jsonResource.getFile(); if (file.canRead() && file.length() > 0) { return MAPPER.readValue(file, Map.class); } } else { LOGGER.warn("JSON resource @ [{}] does not exist", jsonResource); } return new HashMap<>(0); }
@SneakyThrows private void readResourceForInterrupts() { this.interrupts = new LinkedHashMap<>(); if (ResourceUtils.doesResourceExist(resource)) { try (Reader reader = new InputStreamReader(resource.getInputStream(), StandardCharsets.UTF_8)) { final TypeReference<Map<String, InterruptResponse>> personList = new TypeReference<>() { }; this.interrupts = MAPPER.readValue(JsonValue.readHjson(reader).toString(), personList); } } } }
@SneakyThrows private Set<ConsentDecision> readDecisionsFromJsonResource() { if (ResourceUtils.doesResourceExist(jsonResource)) { try (Reader reader = new InputStreamReader(jsonResource.getInputStream(), StandardCharsets.UTF_8)) { final TypeReference<Set<ConsentDecision>> personList = new TypeReference<>() { }; return MAPPER.readValue(JsonValue.readHjson(reader).toString(), personList); } } return new LinkedHashSet<>(0); }
@SneakyThrows private void readTrustedRecordsFromResource() { this.storage = new LinkedHashMap<>(); if (ResourceUtils.doesResourceExist(location)) { try (Reader reader = new InputStreamReader(location.getInputStream(), StandardCharsets.UTF_8)) { val personList = new TypeReference<Map<String, MultifactorAuthenticationTrustRecord>>() { }; this.storage = MAPPER.readValue(JsonValue.readHjson(reader).toString(), personList); } } }
public CasSpringSecurityAuthorizationGenerator(final Resource usersFile) { val properties = new Properties(); try { if (ResourceUtils.doesResourceExist(usersFile)) { properties.load(usersFile.getInputStream()); } } catch (final Exception e) { LOGGER.error(e.getMessage(), e); } this.generator = new SpringSecurityPropertiesAuthorizationGenerator(properties); watchResource(usersFile); }
@SneakyThrows public UmaRequestingPartyTokenSigningService(final Resource jwksFile, final String issuer) { super(issuer); if (ResourceUtils.doesResourceExist(jwksFile)) { val json = IOUtils.toString(jwksFile.getInputStream(), StandardCharsets.UTF_8); val jsonWebKeySet = new JsonWebKeySet(json); val keys = jsonWebKeySet.getJsonWebKeys(); if (keys.isEmpty()) { throw new IllegalArgumentException("No JSON web keys are found in the JWKS keystore " + jwksFile); } this.jsonWebKey = RsaJsonWebKey.class.cast(jsonWebKeySet.getJsonWebKeys().get(0)); } else { LOGGER.warn("JWKS file for UMA RPT tokens is undefined or cannot be located. Tokens will not be signed"); this.jsonWebKey = null; } }
@Override public boolean isAvailable(final SamlRegisteredService service) { if (supports(service)) { val metadataLocation = service.getMetadataLocation(); return ResourceUtils.doesResourceExist(metadataLocation); } return false; } }
@SneakyThrows public WatchableGroovyScriptResource(final Resource script) { this.resource = script; if (ResourceUtils.doesResourceExist(script)) { this.watcherService = new FileWatcherService(script.getFile(), file -> { try { LOGGER.debug("Reloading script at [{}]", file); compileScriptResource(script); } catch (final Exception e) { LOGGER.error(e.getMessage(), e); } }); this.watcherService.start(script.getFilename()); compileScriptResource(script); } }
/** * Sets signing key. If the key provided is resolved as a private key, * then will create use the private key as is, and will sign values * using RSA. Otherwise, AES is used. * * @param signingSecretKey the signing secret key */ protected void configureSigningKey(final String signingSecretKey) { try { if (ResourceUtils.doesResourceExist(signingSecretKey)) { configureSigningKeyFromPrivateKeyResource(signingSecretKey); } } finally { if (this.signingKey == null) { setSigningKey(new AesKey(signingSecretKey.getBytes(StandardCharsets.UTF_8))); LOGGER.trace("Created signing key instance [{}] based on provided secret key", this.signingKey.getClass().getSimpleName()); } } }
@SneakyThrows private static Optional<Pair<Resource, LoggerContext>> buildLoggerContext(final Environment environment, final ResourceLoader resourceLoader) { val logFile = environment.getProperty("logging.config", "classpath:/log4j2.xml"); LOGGER.info("Located logging configuration reference in the environment as [{}]", logFile); if (ResourceUtils.doesResourceExist(logFile, resourceLoader)) { val logConfigurationFile = resourceLoader.getResource(logFile); LOGGER.trace("Loaded logging configuration resource [{}]. Initializing logger context...", logConfigurationFile); val loggerContext = Configurator.initialize("CAS", null, logConfigurationFile.getURI()); LOGGER.trace("Installing log configuration listener to detect changes and update"); loggerContext.getConfiguration().addListener(reconfigurable -> loggerContext.updateLoggers(reconfigurable.reconfigure())); return Optional.of(Pair.of(logConfigurationFile, loggerContext)); } LOGGER.warn("Logging configuration cannot be found in the environment settings"); return Optional.empty(); } }
@Override public PropertySource load() { val props = new Properties(); if (ResourceUtils.doesResourceExist(getResource())) { val pp = CasCoreConfigurationUtils.loadYamlProperties(getResource()); if (pp.isEmpty()) { LOGGER.debug("No properties were located inside [{}]", getResource()); } else { LOGGER.info("Found settings [{}] in YAML file [{}]", pp.keySet(), getResource()); props.putAll(decryptProperties(pp)); } } return finalizeProperties(props); } }
val predicateResource = casProperties.getAuthn().getMfa().getGlobalPrincipalAttributePredicate(); if (predicateResource == null || !ResourceUtils.doesResourceExist(predicateResource)) { LOGGER.debug("No groovy script predicate is defined to decide which multifactor authentication provider should be chosen"); return Optional.empty();
/** * Gets JWKS used to sign RPTs. * * @param request the request * @param response the response * @return redirect view */ @GetMapping(value = '/' + OAuth20Constants.BASE_OAUTH20_URL + "/" + OAuth20Constants.UMA_JWKS_URL, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<String> getKeys(final HttpServletRequest request, final HttpServletResponse response) { try { val jwks = casProperties.getAuthn().getUma().getRequestingPartyToken().getJwksFile(); if (ResourceUtils.doesResourceExist(jwks)) { val jsonJwks = IOUtils.toString(jwks.getInputStream(), StandardCharsets.UTF_8); val jsonWebKeySet = new JsonWebKeySet(jsonJwks); val body = jsonWebKeySet.toJson(JsonWebKey.OutputControlLevel.PUBLIC_ONLY); response.setContentType(MediaType.APPLICATION_JSON_VALUE); return new ResponseEntity<>(body, HttpStatus.OK); } return new ResponseEntity<>("UMA RPT JWKS resource is undefined or cannot be located", HttpStatus.NOT_IMPLEMENTED); } catch (final Exception e) { LOGGER.error(e.getMessage(), e); return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST); } } }
if (!ResourceUtils.doesResourceExist(groovyScript)) { LOGGER.warn("No groovy script is found at [{}] for multifactor authentication", groovyScript); return Optional.empty();
private void configureEncryptionParameters(final String secretKeyEncryption, final String contentEncryptionAlgorithmIdentifier) { var secretKeyToUse = secretKeyEncryption; if (StringUtils.isBlank(secretKeyToUse)) { LOGGER.warn("Secret key for encryption is not defined for [{}]; CAS will attempt to auto-generate the encryption key", getName()); secretKeyToUse = EncodingUtils.generateJsonWebKey(this.encryptionKeySize); LOGGER.warn("Generated encryption key [{}] of size [{}] for [{}]. The generated key MUST be added to CAS settings under setting [{}].", secretKeyToUse, this.encryptionKeySize, getName(), getEncryptionKeySetting()); } else { LOGGER.trace("Located encryption key to use for [{}]", getName()); } try { if (ResourceUtils.doesResourceExist(secretKeyToUse)) { configureEncryptionKeyFromPublicKeyResource(secretKeyToUse); } } catch (final Exception e) { LOGGER.error(e.getMessage(), e); } finally { if (this.secretKeyEncryptionKey == null) { LOGGER.trace("Creating encryption key instance based on provided secret key"); setSecretKeyEncryptionKey(EncodingUtils.generateJsonWebKey(secretKeyToUse)); } setContentEncryptionAlgorithmIdentifier(contentEncryptionAlgorithmIdentifier); LOGGER.trace("Initialized cipher encryption sequence via content encryption [{}] and algorithm [{}]", this.contentEncryptionAlgorithmIdentifier, this.encryptionAlgorithm); } }
@Override public InterruptResponse inquireInternal(final Authentication authentication, final RegisteredService registeredService, final Service service, final Credential credential, final RequestContext requestContext) { if (ResourceUtils.doesResourceExist(watchableScript.getResource())) { val principal = authentication.getPrincipal(); val attributes = new HashMap<String, Object>(principal.getAttributes()); attributes.putAll(authentication.getAttributes()); final Object[] args = {principal.getId(), attributes, service != null ? service.getId() : null, LOGGER}; return watchableScript.execute(args, InterruptResponse.class); } return InterruptResponse.none(); } }
@Bean public EhCacheManagerFactoryBean ehcacheTicketCacheManager() { val cache = casProperties.getTicket().getRegistry().getEhcache(); val bean = new EhCacheManagerFactoryBean(); cache.getSystemProps().forEach((key, value) -> System.setProperty(key, value)); val configExists = ResourceUtils.doesResourceExist(cache.getConfigLocation()); if (configExists) { bean.setConfigLocation(cache.getConfigLocation()); } else { LOGGER.warn("Ehcache configuration file [{}] cannot be found", cache.getConfigLocation()); } bean.setShared(cache.isShared()); bean.setCacheManagerName(cache.getCacheManagerName()); return bean; }
private Ehcache buildCache(final TicketDefinition ticketDefinition) { val cache = casProperties.getTicket().getRegistry().getEhcache(); val configExists = ResourceUtils.doesResourceExist(cache.getConfigLocation()); val ehcacheProperties = casProperties.getTicket().getRegistry().getEhcache(); val bean = new EhCacheFactoryBean(); bean.setCacheName(ticketDefinition.getProperties().getStorageName()); LOGGER.debug("Constructing Ehcache cache [{}]", bean.getName()); if (configExists) { bean.setCacheEventListeners(CollectionUtils.wrapSet(ticketRMISynchronousCacheReplicator())); bean.setBootstrapCacheLoader(ticketCacheBootstrapCacheLoader()); } else { LOGGER.warn("In registering ticket definition [{}], Ehcache configuration file [{}] cannot be found " + "so no cache event listeners will be configured to bootstrap. " + "The ticket registry will operate in standalone mode", ticketDefinition.getPrefix(), cache.getConfigLocation()); } bean.setTimeToIdle((int) ticketDefinition.getProperties().getStorageTimeout()); bean.setTimeToLive((int) ticketDefinition.getProperties().getStorageTimeout()); bean.setDiskExpiryThreadIntervalSeconds(ehcacheProperties.getDiskExpiryThreadIntervalSeconds()); bean.setEternal(ehcacheProperties.isEternal()); bean.setMaxEntriesLocalHeap(ehcacheProperties.getMaxElementsInMemory()); bean.setMaxEntriesInCache(ehcacheProperties.getMaxElementsInCache()); bean.setMaxEntriesLocalDisk(ehcacheProperties.getMaxElementsOnDisk()); bean.setMemoryStoreEvictionPolicy(ehcacheProperties.getMemoryStoreEvictionPolicy()); val c = new PersistenceConfiguration(); c.strategy(ehcacheProperties.getPersistence()); c.setSynchronousWrites(ehcacheProperties.isSynchronousWrites()); bean.persistence(c); bean.afterPropertiesSet(); return bean.getObject(); }