@Override public boolean supports(final Service service) { val svc = this.servicesManager.findServiceBy(service); val res = svc != null && service.getId().startsWith(this.callbackUrl); LOGGER.trace("Authentication request is{} identified as an OAuth request", BooleanUtils.toString(res, StringUtils.EMPTY, " not")); return res; }
@Scheduled( initialDelayString = "${cas.serviceRegistry.schedule.startDelay:20000}", fixedDelayString = "${cas.serviceRegistry.schedule.repeatInterval:60000}" ) @Override public void run() { servicesManager.load(); } }
/** * Return a list of services for the passed domain. * * @param domain the domain name * @return list of services */ default Collection<RegisteredService> getServicesForDomain(final String domain) { return getAllServices(); }
/** * Init service registry if necessary. */ @SuppressFBWarnings("PRMC_POSSIBLY_REDUNDANT_METHOD_CALLS") public void initServiceRegistryIfNecessary() { val size = this.serviceRegistry.size(); LOGGER.trace("Service registry contains [{}] service definition(s)", size); LOGGER.warn("Service registry [{}] will be auto-initialized from JSON service definitions. " + "This behavior is only useful for testing purposes and MAY NOT be appropriate for production. " + "Consider turning off this behavior via the setting [cas.serviceRegistry.initFromJson=false] " + "and explicitly register definitions in the services registry.", this.serviceRegistry.getName()); val servicesLoaded = this.jsonServiceRegistry.load(); LOGGER.debug("Loaded JSON services are [{}]", servicesLoaded.stream().map(RegisteredService::getName).collect(Collectors.joining(","))); servicesLoaded .forEach(r -> { if (!findExistingMatchForService(r)) { LOGGER.debug("Initializing service registry with the [{}] JSON service definition...", r.getName()); this.serviceRegistry.save(r); } }); this.servicesManager.load(); LOGGER.info("Service registry [{}] contains [{}] service definitions", this.serviceRegistry.getName(), this.servicesManager.count()); }
if (this.servicesManager.getAllServices().isEmpty()) { final String msg = String.format("No service definitions are found in the service manager. " + "Service [%s] will not be automatically authorized to request authentication.", service.getId()); throw new UnauthorizedServiceException(UnauthorizedServiceException.CODE_EMPTY_SVC_MGMR, msg); final RegisteredService registeredService = this.servicesManager.findServiceBy(service);
/** * Fetch service either by numeric id or service id pattern. * * @param id the id * @return the registered service */ @ReadOperation(produces = {ActuatorMediaType.V2_JSON, "application/vnd.cas.services+yaml", MediaType.APPLICATION_JSON_VALUE}) public RegisteredService fetchService(@Selector final String id) { if (NumberUtils.isDigits(id)) { return this.servicesManager.findServiceBy(Long.parseLong(id)); } return this.servicesManager.findServiceBy(id); } }
/** * Handle services manager refresh event. * * @param event the event */ @EventListener public void handleRefreshEvent(final CasRegisteredServicesRefreshEvent event) { servicesManager.load(); }
@SuppressFBWarnings("PRMC_POSSIBLY_REDUNDANT_METHOD_CALLS") private static OAuthRegisteredService getRegisteredOAuthServiceByPredicate(final ServicesManager servicesManager, final Predicate<OAuthRegisteredService> predicate) { val services = servicesManager.getAllServices(); return services.stream() .filter(OAuthRegisteredService.class::isInstance) .map(OAuthRegisteredService.class::cast) .filter(predicate) .findFirst() .orElse(null); }
@Override public Set<AuthenticationHandler> resolve(final Set<AuthenticationHandler> candidateHandlers, final AuthenticationTransaction transaction) { val service = transaction.getService(); val registeredService = this.servicesManager.findServiceBy(service); val requiredHandlers = registeredService.getRequiredHandlers(); LOGGER.debug("Authentication transaction requires [{}] for service [{}]", requiredHandlers, service); val handlerSet = new LinkedHashSet<AuthenticationHandler>(candidateHandlers); LOGGER.info("Candidate authentication handlers examined this transaction are [{}]", handlerSet); val it = handlerSet.iterator(); while (it.hasNext()) { val handler = it.next(); val handlerName = handler.getName(); if (!(handler instanceof HttpBasedServiceCredentialsAuthenticationHandler) && !requiredHandlers.contains(handlerName)) { LOGGER.debug("Authentication handler [{}] is not required for this transaction and is removed", handlerName); it.remove(); } } LOGGER.debug("Authentication handlers for this transaction are [{}]", handlerSet); return handlerSet; } }
/** * Handle and produce a list of services from registry. * * @return the web async task */ @ReadOperation(produces = {ActuatorMediaType.V2_JSON, "application/vnd.cas.services+yaml", MediaType.APPLICATION_JSON_VALUE}) public Collection<RegisteredService> handle() { return this.servicesManager.load(); }
/** * Overrideable method to determine which credentials to use to grant a * proxy granting ticket. Default is to use the pgtUrl. * * @param service the webapp service requesting proxy * @param request the HttpServletRequest object. * @return the credentials or null if there was an error or no credentials * provided. */ protected Credential getServiceCredentialsFromRequest(final WebApplicationService service, final HttpServletRequest request) { val pgtUrl = request.getParameter(CasProtocolConstants.PARAMETER_PROXY_CALLBACK_URL); if (StringUtils.isNotBlank(pgtUrl)) { try { val registeredService = this.servicesManager.findServiceBy(service); verifyRegisteredServiceProperties(registeredService, service); return new HttpBasedServiceCredential(new URL(pgtUrl), registeredService); } catch (final Exception e) { LOGGER.error("Error constructing [{}]", CasProtocolConstants.PARAMETER_PROXY_CALLBACK_URL, e); } } return null; }
private ServicesManager createJSONServiceManager(final GitUtil git) { val path = Paths.get(git.repoPath()); val serviceRegistryDAO = new JsonServiceRegistry(path, false, null, null, namingStrategy); val manager = (ServicesManager) (casProperties.getServiceRegistry().getManagementType() == ServiceRegistryProperties.ServiceManagementTypes.DOMAIN ? new DomainServicesManager(serviceRegistryDAO, null, new HashSet<>()) : new DefaultServicesManager(serviceRegistryDAO, null, new HashSet<>())); manager.load(); return manager; }
/** * Gets registered service from request. * Reading the request body by the argument extractor here may cause the underlying request stream * to close. If there are any underlying controllers or components that expect to read * or parse the request body, like those that handle ticket validation, they would fail given the * {@link HttpServletRequest#getReader()} is consumed by the argument extractor here and not available anymore. * Therefor, any of the inner components of the extractor might have to cache the request body * as an attribute, etc so they can re-process and re-extract as needed. * * @param request the request * @return the registered service from request */ private Optional<RegisteredService> getRegisteredServiceFromRequest(final HttpServletRequest request) { val service = this.argumentExtractor.extractService(request); if (service != null) { val resolved = authenticationRequestServiceSelectionStrategies.resolveService(service); return Optional.ofNullable(this.servicesManager.findServiceBy(resolved)); } return Optional.empty(); } }
try (val zipfs = FileSystems.newFileSystem(URI.create("jar:" + file.toURI().toString()), env)) { val serializer = new DefaultRegisteredServiceJsonSerializer(); val services = this.servicesManager.load(); services.forEach(Unchecked.consumer(service -> { val fileName = String.format("%s-%s", service.getName(), service.getId());
/** * Resolve registered service in request context. * * @param requestContext the request context * @return the registered service */ protected RegisteredService resolveRegisteredServiceInRequestContext(final RequestContext requestContext) { val resolvedService = resolveServiceFromAuthenticationRequest(requestContext); if (resolvedService != null) { val service = this.servicesManager.findServiceBy(resolvedService); RegisteredServiceAccessStrategyUtils.ensureServiceAccessIsAllowed(resolvedService, service); return service; } LOGGER.debug("Authentication request is not accompanied by a service given none is specified"); return null; } }
servicesManager.load();
@Bean @ConditionalOnMissingBean(name = "requestedContextValidator") public RequestedContextValidator requestedContextValidator() { return (assertion, request) -> { LOGGER.debug("Locating the primary authentication associated with this service request [{}]", assertion.getService()); val service = servicesManager.getIfAvailable().findServiceBy(assertion.getService()); RegisteredServiceAccessStrategyUtils.ensureServiceAccessIsAllowed(assertion.getService(), service); return Pair.of(Boolean.TRUE, Optional.empty()); }; } }
/** * Prepare cas response attributes for view model. * * @param model the model */ protected void prepareCasResponseAttributesForViewModel(final Map<String, Object> model) { val service = authenticationRequestServiceSelectionStrategies.resolveService(getServiceFrom(model)); val registeredService = this.servicesManager.findServiceBy(service); val principalAttributes = getCasPrincipalAttributes(model, registeredService); val attributes = new HashMap<String, Object>(principalAttributes); LOGGER.trace("Processed principal attributes from the output model to be [{}]", principalAttributes.keySet()); val protocolAttributes = getCasProtocolAuthenticationAttributes(model, registeredService); attributes.putAll(protocolAttributes); LOGGER.debug("Final collection of attributes for the response are [{}].", attributes.keySet()); putCasResponseAttributesIntoModel(model, attributes, registeredService, this.attributesRenderer); }
/** * Prepare saml attributes. Combines both principal and authentication * attributes. * * @param model the model * @return the final map * @since 4.1.0 */ private Map<String, Object> prepareSamlAttributes(final Map<String, Object> model, final Service service) { val registeredService = this.servicesManager.findServiceBy(service); val authnAttributes = getCasProtocolAuthenticationAttributes(model, registeredService); LOGGER.debug("Retrieved authentication attributes [{}] from the model", authnAttributes); val attributesToReturn = new HashMap<String, Object>(); attributesToReturn.putAll(getPrincipalAttributesAsMultiValuedAttributes(model)); attributesToReturn.putAll(authnAttributes); LOGGER.debug("Beginning to encode attributes [{}] for service [{}]", attributesToReturn, registeredService.getServiceId()); val finalAttributes = this.protocolAttributeEncoder.encodeAttributes(attributesToReturn, registeredService); LOGGER.debug("Final collection of attributes are [{}]", finalAttributes); return finalAttributes; }
/** * Finalize profile response. * * @param accessTokenTicket the access token ticket * @param map the map * @param principal the authentication principal */ protected void finalizeProfileResponse(final AccessToken accessTokenTicket, final Map<String, Object> map, final Principal principal) { val service = accessTokenTicket.getService(); val registeredService = servicesManager.findServiceBy(service); if (registeredService instanceof OAuthRegisteredService) { val oauth = (OAuthRegisteredService) registeredService; map.put(OAuth20Constants.CLIENT_ID, oauth.getClientId()); map.put(CasProtocolConstants.PARAMETER_SERVICE, service.getId()); } } }