idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
18,100 | protected OAuthRegisteredService getOAuthRegisteredServiceBy ( final HttpServletRequest request ) { val redirectUri = getRegisteredServiceIdentifierFromRequest ( request ) ; val registeredService = OAuth20Utils . getRegisteredOAuthServiceByRedirectUri ( getOAuthConfigurationContext ( ) . getServicesManager ( ) , redirectUri ) ; LOGGER . debug ( "Located registered service [{}]" , registeredService ) ; return registeredService ; } | Gets oauth registered service from the request . Implementation attempts to locate the redirect uri from request and check with service registry to find a matching oauth service . |
18,101 | public static String buildTypeSourcePath ( final String sourcePath , final String type ) { val newName = type . replace ( "." , File . separator ) ; return sourcePath + "/src/main/java/" + newName + ".java" ; } | Build type source path string . |
18,102 | public Class locatePropertiesClassForType ( final ClassOrInterfaceType type ) { if ( cachedPropertiesClasses . containsKey ( type . getNameAsString ( ) ) ) { return cachedPropertiesClasses . get ( type . getNameAsString ( ) ) ; } val packageName = ConfigurationMetadataGenerator . class . getPackage ( ) . getName ( ) ; val reflections = new Reflections ( new ConfigurationBuilder ( ) . filterInputsBy ( s -> s != null && s . contains ( type . getNameAsString ( ) ) ) . setUrls ( ClasspathHelper . forPackage ( packageName ) ) . setScanners ( new TypeElementsScanner ( ) . includeFields ( false ) . includeMethods ( false ) . includeAnnotations ( false ) . filterResultsBy ( s -> s != null && s . endsWith ( type . getNameAsString ( ) ) ) , new SubTypesScanner ( false ) ) ) ; val clz = reflections . getSubTypesOf ( Serializable . class ) . stream ( ) . filter ( c -> c . getSimpleName ( ) . equalsIgnoreCase ( type . getNameAsString ( ) ) ) . findFirst ( ) . orElseThrow ( ( ) -> new IllegalArgumentException ( "Cant locate class for " + type . getNameAsString ( ) ) ) ; cachedPropertiesClasses . put ( type . getNameAsString ( ) , clz ) ; return clz ; } | Locate properties class for type class . |
18,103 | public BaseConfigurationPropertiesLoader getLoader ( final Resource resource , final String name ) { val filename = StringUtils . defaultString ( resource . getFilename ( ) ) . toLowerCase ( ) ; if ( filename . endsWith ( ".properties" ) ) { return new SimpleConfigurationPropertiesLoader ( this . configurationCipherExecutor , name , resource ) ; } if ( filename . endsWith ( ".groovy" ) ) { return new GroovyConfigurationPropertiesLoader ( this . configurationCipherExecutor , name , getApplicationProfiles ( environment ) , resource ) ; } if ( filename . endsWith ( ".yaml" ) || filename . endsWith ( ".yml" ) ) { return new YamlConfigurationPropertiesLoader ( this . configurationCipherExecutor , name , resource ) ; } throw new IllegalArgumentException ( "Unable to determine configuration loader for " + resource ) ; } | Gets loader . |
18,104 | public static List < String > getApplicationProfiles ( final Environment environment ) { return Arrays . stream ( environment . getActiveProfiles ( ) ) . collect ( Collectors . toList ( ) ) ; } | Gets application profiles . |
18,105 | public Collection < Ticket > getTokens ( ) { return ticketRegistry . getTickets ( ticket -> ( ticket instanceof AccessToken || ticket instanceof RefreshToken ) && ! ticket . isExpired ( ) ) . sorted ( Comparator . comparing ( Ticket :: getId ) ) . collect ( Collectors . toList ( ) ) ; } | Gets access tokens . |
18,106 | public Ticket getToken ( final String ticketId ) { var ticket = ( Ticket ) ticketRegistry . getTicket ( ticketId , AccessToken . class ) ; if ( ticket == null ) { ticket = ticketRegistry . getTicket ( ticketId , RefreshToken . class ) ; } if ( ticket == null ) { LOGGER . debug ( "Ticket [{}] is not found" , ticketId ) ; return null ; } if ( ticket . isExpired ( ) ) { LOGGER . debug ( "Ticket [{}] is has expired" , ticketId ) ; return null ; } return ticket ; } | Gets access token . |
18,107 | public void deleteToken ( final String ticketId ) { val ticket = getToken ( ticketId ) ; if ( ticket != null ) { ticketRegistry . deleteTicket ( ticketId ) ; } } | Delete access token . |
18,108 | public OneTimeTokenAccount create ( final String username ) { val key = getGoogleAuthenticator ( ) . createCredentials ( ) ; return new GoogleAuthenticatorAccount ( username , key . getKey ( ) , key . getVerificationCode ( ) , key . getScratchCodes ( ) ) ; } | Create one time token account . |
18,109 | protected ProcessedClaim createProcessedClaim ( final Claim requestClaim , final ClaimsParameters parameters ) { val claim = new ProcessedClaim ( ) ; claim . setClaimType ( createProcessedClaimType ( requestClaim , parameters ) ) ; claim . setIssuer ( this . issuer ) ; claim . setOriginalIssuer ( this . issuer ) ; claim . setValues ( requestClaim . getValues ( ) ) ; return claim ; } | Create processed claim processed claim . |
18,110 | @ PostMapping ( value = "/v1/services" , consumes = MediaType . APPLICATION_JSON_VALUE ) public ResponseEntity < String > createService ( final RegisteredService service , final HttpServletRequest request , final HttpServletResponse response ) { try { val auth = authenticateRequest ( request , response ) ; if ( isAuthenticatedPrincipalAuthorized ( auth ) ) { this . servicesManager . save ( service ) ; return new ResponseEntity < > ( HttpStatus . OK ) ; } return new ResponseEntity < > ( "Request is not authorized" , HttpStatus . FORBIDDEN ) ; } catch ( final AuthenticationException e ) { return new ResponseEntity < > ( e . getMessage ( ) , HttpStatus . UNAUTHORIZED ) ; } catch ( final Exception e ) { LOGGER . error ( e . getMessage ( ) , e ) ; return new ResponseEntity < > ( e . getMessage ( ) , HttpStatus . BAD_REQUEST ) ; } } | Create new service . |
18,111 | public String determinePrincipalIdFromAttributes ( final String defaultId , final Map < String , List < Object > > attributes ) { return FunctionUtils . doIf ( StringUtils . isNotBlank ( this . attribute ) && attributes . containsKey ( this . attribute ) , ( ) -> { val attributeValue = attributes . get ( this . attribute ) ; LOGGER . debug ( "Using attribute [{}] to establish principal id" , this . attribute ) ; return CollectionUtils . firstElement ( attributeValue ) . get ( ) . toString ( ) ; } , ( ) -> { LOGGER . debug ( "Using principal id [{}] to generate persistent identifier" , defaultId ) ; return defaultId ; } ) . get ( ) ; } | Determine principal id from attributes . |
18,112 | protected String digestAndEncodeWithSalt ( final MessageDigest md ) { val sanitizedSalt = StringUtils . replace ( salt , "\n" , " " ) ; val digested = md . digest ( sanitizedSalt . getBytes ( StandardCharsets . UTF_8 ) ) ; return EncodingUtils . encodeBase64 ( digested , false ) ; } | Digest and encode with salt string . |
18,113 | protected static MessageDigest prepareMessageDigest ( final String principal , final String service ) throws NoSuchAlgorithmException { val md = MessageDigest . getInstance ( "SHA" ) ; if ( StringUtils . isNotBlank ( service ) ) { md . update ( service . getBytes ( StandardCharsets . UTF_8 ) ) ; md . update ( CONST_SEPARATOR ) ; } md . update ( principal . getBytes ( StandardCharsets . UTF_8 ) ) ; md . update ( CONST_SEPARATOR ) ; return md ; } | Prepare message digest message digest . |
18,114 | public void write ( final Point point ) { this . influxDb . write ( influxDbProperties . getDatabase ( ) , influxDbProperties . getRetentionPolicy ( ) , point ) ; } | Write measurement point . |
18,115 | public void writeBatch ( final Point ... point ) { val batchPoints = BatchPoints . database ( influxDbProperties . getDatabase ( ) ) . retentionPolicy ( influxDbProperties . getRetentionPolicy ( ) ) . consistency ( InfluxDB . ConsistencyLevel . valueOf ( influxDbProperties . getConsistencyLevel ( ) ) ) . build ( ) ; Arrays . stream ( point ) . forEach ( batchPoints :: point ) ; influxDb . write ( batchPoints ) ; } | Write synchronized batch . |
18,116 | protected Map < String , Object > findAccountViaRestApi ( final Map < String , Object > headers ) { HttpResponse response = null ; try { response = HttpUtils . execute ( properties . getUrl ( ) , properties . getMethod ( ) , properties . getBasicAuthUsername ( ) , properties . getBasicAuthPassword ( ) , new HashMap < > ( ) , headers ) ; if ( response != null && response . getEntity ( ) != null && response . getStatusLine ( ) . getStatusCode ( ) == HttpStatus . SC_OK ) { return MAPPER . readValue ( response . getEntity ( ) . getContent ( ) , Map . class ) ; } } catch ( final Exception e ) { LOGGER . error ( e . getMessage ( ) , e ) ; } finally { HttpUtils . close ( response ) ; } return new HashMap < > ( ) ; } | Find account via rest api and return user - info map . |
18,117 | public static < K , V > RedisTemplate < K , V > newRedisTemplate ( final RedisConnectionFactory connectionFactory ) { val template = new RedisTemplate < K , V > ( ) ; val string = new StringRedisSerializer ( ) ; val jdk = new JdkSerializationRedisSerializer ( ) ; template . setKeySerializer ( string ) ; template . setValueSerializer ( jdk ) ; template . setHashValueSerializer ( jdk ) ; template . setHashKeySerializer ( string ) ; template . setConnectionFactory ( connectionFactory ) ; return template ; } | New redis template . |
18,118 | public static RedisConnectionFactory newRedisConnectionFactory ( final BaseRedisProperties redis ) { val redisConfiguration = redis . getSentinel ( ) == null ? ( RedisConfiguration ) getStandaloneConfig ( redis ) : getSentinelConfig ( redis ) ; val factory = new LettuceConnectionFactory ( redisConfiguration , getRedisPoolConfig ( redis ) ) ; return factory ; } | New redis connection factory . |
18,119 | @ 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 ( ) ) ; } | Init service registry if necessary . |
18,120 | public void execute ( ) { OrderComparator . sortIfNecessary ( webflowConfigurers ) ; webflowConfigurers . forEach ( c -> { LOGGER . trace ( "Registering webflow configurer [{}]" , c . getName ( ) ) ; c . initialize ( ) ; } ) ; } | Execute the plan . |
18,121 | private static AbstractWebApplicationService determineWebApplicationFormat ( final HttpServletRequest request , final AbstractWebApplicationService webApplicationService ) { val format = request != null ? request . getParameter ( CasProtocolConstants . PARAMETER_FORMAT ) : null ; try { if ( StringUtils . isNotBlank ( format ) ) { val formatType = ValidationResponseType . valueOf ( format . toUpperCase ( ) ) ; webApplicationService . setFormat ( formatType ) ; } } catch ( final Exception e ) { LOGGER . error ( "Format specified in the request [{}] is not recognized" , format ) ; } return webApplicationService ; } | Determine web application format boolean . |
18,122 | protected static AbstractWebApplicationService newWebApplicationService ( final HttpServletRequest request , final String serviceToUse ) { val artifactId = request != null ? request . getParameter ( CasProtocolConstants . PARAMETER_TICKET ) : null ; val id = cleanupUrl ( serviceToUse ) ; val newService = new SimpleWebApplicationServiceImpl ( id , serviceToUse , artifactId ) ; determineWebApplicationFormat ( request , newService ) ; val source = getSourceParameter ( request , CasProtocolConstants . PARAMETER_TARGET_SERVICE , CasProtocolConstants . PARAMETER_SERVICE ) ; newService . setSource ( source ) ; return newService ; } | Build new web application service simple web application service . |
18,123 | protected String getRequestedService ( final HttpServletRequest request ) { val targetService = request . getParameter ( CasProtocolConstants . PARAMETER_TARGET_SERVICE ) ; val service = request . getParameter ( CasProtocolConstants . PARAMETER_SERVICE ) ; val serviceAttribute = request . getAttribute ( CasProtocolConstants . PARAMETER_SERVICE ) ; if ( StringUtils . isNotBlank ( targetService ) ) { return targetService ; } if ( StringUtils . isNotBlank ( service ) ) { return service ; } if ( serviceAttribute != null ) { if ( serviceAttribute instanceof Service ) { return ( ( Service ) serviceAttribute ) . getId ( ) ; } return serviceAttribute . toString ( ) ; } return null ; } | Gets requested service . |
18,124 | public TransientSessionTicket create ( final Service service , final Map < String , Serializable > properties ) { val id = ticketIdGenerator . getNewTicketId ( "CAS" ) ; return new TransientSessionTicketImpl ( id , expirationPolicy , service , properties ) ; } | Create delegated authentication request ticket . |
18,125 | protected static boolean locateMatchingAttributeBasedOnAuthenticationAttributes ( final MultifactorAuthenticationProviderBypassProperties bypass , final Authentication authn ) { return locateMatchingAttributeValue ( bypass . getAuthenticationAttributeName ( ) , bypass . getAuthenticationAttributeValue ( ) , authn . getAttributes ( ) , false ) ; } | Skip bypass and support event based on authentication attributes . |
18,126 | public void postLoad ( ) { if ( principalAttributesRepository == null ) { this . principalAttributesRepository = new DefaultPrincipalAttributesRepository ( ) ; } if ( consentPolicy == null ) { this . consentPolicy = new DefaultRegisteredServiceConsentPolicy ( ) ; } } | Post load after having loaded the bean via JPA etc . |
18,127 | protected Map < String , List < Object > > resolveAttributesFromPrincipalAttributeRepository ( final Principal principal , final RegisteredService registeredService ) { val repository = ObjectUtils . defaultIfNull ( this . principalAttributesRepository , getPrincipalAttributesRepositoryFromApplicationContext ( ) ) ; if ( repository != null ) { LOGGER . debug ( "Using principal attribute repository [{}] to retrieve attributes" , repository ) ; return repository . getAttributes ( principal , registeredService ) ; } return principal . getAttributes ( ) ; } | Resolve attributes from principal attribute repository . |
18,128 | protected void insertPrincipalIdAsAttributeIfNeeded ( final Principal principal , final Map < String , List < Object > > attributesToRelease , final Service service , final RegisteredService registeredService ) { if ( StringUtils . isNotBlank ( getPrincipalIdAttribute ( ) ) ) { LOGGER . debug ( "Attempting to resolve the principal id for service [{}]" , registeredService . getServiceId ( ) ) ; val id = registeredService . getUsernameAttributeProvider ( ) . resolveUsername ( principal , service , registeredService ) ; LOGGER . debug ( "Releasing resolved principal id [{}] as attribute [{}]" , id , getPrincipalIdAttribute ( ) ) ; attributesToRelease . put ( getPrincipalIdAttribute ( ) , CollectionUtils . wrapList ( principal . getId ( ) ) ) ; } } | Release principal id as attribute if needed . |
18,129 | protected Map < String , List < Object > > returnFinalAttributesCollection ( final Map < String , List < Object > > attributesToRelease , final RegisteredService service ) { LOGGER . debug ( "Final collection of attributes allowed are: [{}]" , attributesToRelease ) ; return attributesToRelease ; } | Return the final attributes collection . Subclasses may override this minute to impose last minute rules . |
18,130 | protected Map < String , List < Object > > getReleasedByDefaultAttributes ( final Principal p , final Map < String , List < Object > > attributes ) { val ctx = ApplicationContextProvider . getApplicationContext ( ) ; if ( ctx != null ) { LOGGER . trace ( "Located application context. Retrieving default attributes for release, if any" ) ; val props = ctx . getAutowireCapableBeanFactory ( ) . getBean ( CasConfigurationProperties . class ) ; val defaultAttrs = props . getAuthn ( ) . getAttributeRepository ( ) . getDefaultAttributesToRelease ( ) ; LOGGER . debug ( "Default attributes for release are: [{}]" , defaultAttrs ) ; val defaultAttributesToRelease = new TreeMap < String , List < Object > > ( String . CASE_INSENSITIVE_ORDER ) ; defaultAttrs . forEach ( key -> { if ( attributes . containsKey ( key ) ) { LOGGER . debug ( "Found and added default attribute for release: [{}]" , key ) ; defaultAttributesToRelease . put ( key , attributes . get ( key ) ) ; } } ) ; return defaultAttributesToRelease ; } return new TreeMap < > ( ) ; } | Determines a default bundle of attributes that may be released to all services without the explicit mapping for each service . |
18,131 | public < T > T build ( final AwsClientBuilder builder , final Class < T > clientType ) { val cfg = new ClientConfiguration ( ) ; try { val localAddress = getSetting ( "localAddress" ) ; if ( StringUtils . isNotBlank ( localAddress ) ) { cfg . setLocalAddress ( InetAddress . getByName ( localAddress ) ) ; } } catch ( final Exception e ) { LOGGER . error ( e . getMessage ( ) , e ) ; } builder . withClientConfiguration ( cfg ) ; val key = getSetting ( "credentialAccessKey" ) ; val secret = getSetting ( "credentialSecretKey" ) ; val credentials = ChainingAWSCredentialsProvider . getInstance ( key , secret ) ; builder . withCredentials ( credentials ) ; var region = getSetting ( "region" ) ; val currentRegion = Regions . getCurrentRegion ( ) ; if ( currentRegion != null && StringUtils . isBlank ( region ) ) { region = currentRegion . getName ( ) ; } var regionOverride = getSetting ( "regionOverride" ) ; if ( currentRegion != null && StringUtils . isNotBlank ( regionOverride ) ) { regionOverride = currentRegion . getName ( ) ; } val finalRegion = StringUtils . defaultIfBlank ( regionOverride , region ) ; if ( StringUtils . isNotBlank ( finalRegion ) ) { builder . withRegion ( finalRegion ) ; } val endpoint = getSetting ( "endpoint" ) ; if ( StringUtils . isNotBlank ( endpoint ) ) { builder . withEndpointConfiguration ( new AwsClientBuilder . EndpointConfiguration ( endpoint , finalRegion ) ) ; } val result = builder . build ( ) ; return clientType . cast ( result ) ; } | Build the client . |
18,132 | private static double submissionRate ( final ZonedDateTime a , final ZonedDateTime b ) { return SUBMISSION_RATE_DIVIDEND / ( a . toInstant ( ) . toEpochMilli ( ) - b . toInstant ( ) . toEpochMilli ( ) ) ; } | Computes the instantaneous rate in between two given dates corresponding to two submissions . |
18,133 | public void decrement ( ) { LOGGER . info ( "Beginning audit cleanup..." ) ; val now = ZonedDateTime . now ( ZoneOffset . UTC ) ; this . ipMap . entrySet ( ) . removeIf ( entry -> submissionRate ( now , entry . getValue ( ) ) < getThresholdRate ( ) ) ; LOGGER . debug ( "Done decrementing count for throttler." ) ; } | This class relies on an external configuration to clean it up . It ignores the threshold data in the parent class . |
18,134 | private static Reason getReasonFromX509Entry ( final X509CRLEntry entry ) { if ( entry . hasExtensions ( ) ) { try { val code = Integer . parseInt ( new String ( entry . getExtensionValue ( CRL_REASON_OID ) , "ASCII" ) ) ; if ( code < Reason . values ( ) . length ) { return Reason . fromCode ( code ) ; } } catch ( final Exception e ) { LOGGER . trace ( "An exception occurred when resolving extension value: [{}]" , e . getMessage ( ) ) ; } } return null ; } | Get reason from the x509 entry . |
18,135 | public static HibernateJpaVendorAdapter newHibernateJpaVendorAdapter ( final DatabaseProperties databaseProperties ) { val bean = new HibernateJpaVendorAdapter ( ) ; bean . setGenerateDdl ( databaseProperties . isGenDdl ( ) ) ; bean . setShowSql ( databaseProperties . isShowSql ( ) ) ; return bean ; } | New hibernate jpa vendor adapter . |
18,136 | public static LocalContainerEntityManagerFactoryBean newHibernateEntityManagerFactoryBean ( final JpaConfigDataHolder config , final AbstractJpaProperties jpaProperties ) { val bean = new LocalContainerEntityManagerFactoryBean ( ) ; bean . setJpaVendorAdapter ( config . getJpaVendorAdapter ( ) ) ; if ( StringUtils . isNotBlank ( config . getPersistenceUnitName ( ) ) ) { bean . setPersistenceUnitName ( config . getPersistenceUnitName ( ) ) ; } bean . setPackagesToScan ( config . getPackagesToScan ( ) . toArray ( ArrayUtils . EMPTY_STRING_ARRAY ) ) ; if ( config . getDataSource ( ) != null ) { bean . setDataSource ( config . getDataSource ( ) ) ; } val properties = new Properties ( ) ; properties . put ( Environment . DIALECT , jpaProperties . getDialect ( ) ) ; properties . put ( Environment . HBM2DDL_AUTO , jpaProperties . getDdlAuto ( ) ) ; properties . put ( Environment . STATEMENT_BATCH_SIZE , jpaProperties . getBatchSize ( ) ) ; if ( StringUtils . isNotBlank ( jpaProperties . getDefaultCatalog ( ) ) ) { properties . put ( Environment . DEFAULT_CATALOG , jpaProperties . getDefaultCatalog ( ) ) ; } if ( StringUtils . isNotBlank ( jpaProperties . getDefaultSchema ( ) ) ) { properties . put ( Environment . DEFAULT_SCHEMA , jpaProperties . getDefaultSchema ( ) ) ; } properties . put ( Environment . ENABLE_LAZY_LOAD_NO_TRANS , Boolean . TRUE ) ; properties . put ( Environment . FORMAT_SQL , Boolean . TRUE ) ; properties . put ( "hibernate.connection.useUnicode" , Boolean . TRUE ) ; properties . put ( "hibernate.connection.characterEncoding" , StandardCharsets . UTF_8 . name ( ) ) ; properties . put ( "hibernate.connection.charSet" , StandardCharsets . UTF_8 . name ( ) ) ; if ( StringUtils . isNotBlank ( jpaProperties . getPhysicalNamingStrategyClassName ( ) ) ) { properties . put ( Environment . PHYSICAL_NAMING_STRATEGY , jpaProperties . getPhysicalNamingStrategyClassName ( ) ) ; } properties . putAll ( jpaProperties . getProperties ( ) ) ; bean . setJpaProperties ( properties ) ; return bean ; } | New entity manager factory bean . |
18,137 | public Response createResponse ( final String serviceId , final WebApplicationService service ) { return this . samlObjectBuilder . newResponse ( this . samlObjectBuilder . generateSecureRandomId ( ) , ZonedDateTime . now ( ZoneOffset . UTC ) . minusSeconds ( this . skewAllowance ) , serviceId , service ) ; } | Create response . |
18,138 | public void setStatusRequestDenied ( final Response response , final String description ) { response . setStatus ( this . samlObjectBuilder . newStatus ( StatusCode . REQUEST_DENIED , description ) ) ; } | Sets status request denied . |
18,139 | public void prepareSuccessfulResponse ( final Response response , final Service service , final Authentication authentication , final Principal principal , final Map < String , List < Object > > authnAttributes , final Map < String , List < Object > > principalAttributes ) { val issuedAt = DateTimeUtils . zonedDateTimeOf ( response . getIssueInstant ( ) ) ; LOGGER . debug ( "Preparing SAML response for service [{}]" , service ) ; final Collection < Object > authnMethods = CollectionUtils . toCollection ( authentication . getAttributes ( ) . get ( SamlAuthenticationMetaDataPopulator . ATTRIBUTE_AUTHENTICATION_METHOD ) ) ; LOGGER . debug ( "Authentication methods found are [{}]" , authnMethods ) ; val authnStatement = this . samlObjectBuilder . newAuthenticationStatement ( authentication . getAuthenticationDate ( ) , authnMethods , principal . getId ( ) ) ; LOGGER . debug ( "Built authentication statement for [{}] dated at [{}]" , principal , authentication . getAuthenticationDate ( ) ) ; val assertion = this . samlObjectBuilder . newAssertion ( authnStatement , this . issuer , issuedAt , this . samlObjectBuilder . generateSecureRandomId ( ) ) ; LOGGER . debug ( "Built assertion for issuer [{}] dated at [{}]" , this . issuer , issuedAt ) ; val conditions = this . samlObjectBuilder . newConditions ( issuedAt , service . getId ( ) , this . issueLength ) ; assertion . setConditions ( conditions ) ; LOGGER . debug ( "Built assertion conditions for issuer [{}] and service [{}] " , this . issuer , service . getId ( ) ) ; val subject = this . samlObjectBuilder . newSubject ( principal . getId ( ) ) ; LOGGER . debug ( "Built subject for principal [{}]" , principal ) ; val attributesToSend = prepareSamlAttributes ( service , authnAttributes , principalAttributes ) ; LOGGER . debug ( "Authentication statement shall include these attributes [{}]" , attributesToSend ) ; if ( ! attributesToSend . isEmpty ( ) ) { assertion . getAttributeStatements ( ) . add ( this . samlObjectBuilder . newAttributeStatement ( subject , attributesToSend , this . defaultAttributeNamespace ) ) ; } response . setStatus ( this . samlObjectBuilder . newStatus ( StatusCode . SUCCESS , null ) ) ; LOGGER . debug ( "Set response status code to [{}]" , response . getStatus ( ) ) ; response . getAssertions ( ) . add ( assertion ) ; } | Prepare successful response . |
18,140 | public void encodeSamlResponse ( final Response samlResponse , final HttpServletRequest request , final HttpServletResponse response ) throws Exception { this . samlObjectBuilder . encodeSamlResponse ( response , request , samlResponse ) ; } | Encode saml response . |
18,141 | @ ShellMethod ( key = "generate-idp-metadata" , value = "Generate SAML2 IdP Metadata" ) public void generate ( @ ShellOption ( value = { "metadataLocation" } , help = "Directory location to hold metadata and relevant keys/certificates" , defaultValue = "/etc/cas/saml" ) final String metadataLocation , @ ShellOption ( value = { "entityId" } , help = "Entity ID to use for the generated metadata" , defaultValue = "cas.example.org" ) final String entityId , @ ShellOption ( value = { "hostName" } , help = "CAS server prefix to be used at the IdP host name when generating metadata" , defaultValue = "https://cas.example.org/cas" ) final String serverPrefix , @ ShellOption ( value = { "scope" } , help = "Scope to use when generating metadata" , defaultValue = "example.org" ) final String scope , @ ShellOption ( value = { "force" } , help = "Force metadata generation, disregarding anything that might already be available at the specified location" ) final boolean force ) { val locator = new FileSystemSamlIdPMetadataLocator ( new File ( metadataLocation ) ) ; val writer = new DefaultSamlIdPCertificateAndKeyWriter ( ) ; val context = SamlIdPMetadataGeneratorConfigurationContext . builder ( ) . samlIdPMetadataLocator ( locator ) . samlIdPCertificateAndKeyWriter ( writer ) . entityId ( entityId ) . resourceLoader ( resourceLoader ) . casServerPrefix ( serverPrefix ) . scope ( scope ) . metadataCipherExecutor ( CipherExecutor . noOpOfStringToString ( ) ) . build ( ) ; val generator = new FileSystemSamlIdPMetadataGenerator ( context ) ; val generateMetadata = FunctionUtils . doIf ( locator . exists ( ) , ( ) -> Boolean . TRUE , ( ) -> { LOGGER . warn ( "Metadata artifacts are available at the specified location: [{}]" , metadataLocation ) ; return force ; } ) . get ( ) ; if ( generateMetadata ) { generator . initialize ( ) ; generator . generate ( ) ; LOGGER . info ( "Generated metadata is available at [{}]" , locator . getMetadata ( ) ) ; } else { LOGGER . info ( "No metadata was generated; it might already exist at the specified path" ) ; } } | Generate saml2 idp metadata at the specified location . |
18,142 | public boolean email ( final Principal principal , final String attribute , final EmailProperties emailProperties , final String body ) { if ( StringUtils . isNotBlank ( attribute ) && principal . getAttributes ( ) . containsKey ( attribute ) && isMailSenderDefined ( ) ) { val to = getFirstAttributeByName ( principal , attribute ) ; if ( to . isPresent ( ) ) { return email ( emailProperties , to . get ( ) . toString ( ) , body ) ; } } LOGGER . debug ( "Email attribute [{}] cannot be found or no configuration for email provider is defined" , attribute ) ; return false ; } | Email boolean . |
18,143 | protected Principal getPrincipal ( final String name , final boolean isNtlm ) { if ( this . principalWithDomainName ) { return this . principalFactory . createPrincipal ( name ) ; } if ( isNtlm ) { if ( Pattern . matches ( "\\S+\\\\\\S+" , name ) ) { val splitList = Splitter . on ( Pattern . compile ( "\\\\" ) ) . splitToList ( name ) ; if ( splitList . size ( ) == 2 ) { return this . principalFactory . createPrincipal ( splitList . get ( 1 ) ) ; } } return this . principalFactory . createPrincipal ( name ) ; } val splitList = Splitter . on ( "@" ) . splitToList ( name ) ; return this . principalFactory . createPrincipal ( splitList . get ( 0 ) ) ; } | Gets the principal from the given name . The principal is created by the factory instance . |
18,144 | public JwtTicketCipherExecutor getTokenTicketCipherExecutorForService ( final RegisteredService registeredService ) { val encryptionKey = getEncryptionKey ( registeredService ) . orElse ( StringUtils . EMPTY ) ; val signingKey = getSigningKey ( registeredService ) . orElse ( StringUtils . EMPTY ) ; return new JwtTicketCipherExecutor ( encryptionKey , signingKey , StringUtils . isNotBlank ( encryptionKey ) , StringUtils . isNotBlank ( signingKey ) , 0 , 0 ) ; } | Gets token ticket cipher executor for service . |
18,145 | public Optional < String > getSigningKey ( final RegisteredService registeredService ) { val property = getSigningKeyRegisteredServiceProperty ( ) ; if ( property . isAssignedTo ( registeredService ) ) { val signingKey = property . getPropertyValue ( registeredService ) . getValue ( ) ; return Optional . of ( signingKey ) ; } return Optional . empty ( ) ; } | Gets signing key . |
18,146 | public Optional < String > getEncryptionKey ( final RegisteredService registeredService ) { val property = getEncryptionKeyRegisteredServiceProperty ( ) ; if ( property . isAssignedTo ( registeredService ) ) { val key = property . getPropertyValue ( registeredService ) . getValue ( ) ; return Optional . of ( key ) ; } return Optional . empty ( ) ; } | Gets encryption key . |
18,147 | protected String encodeAndFinalizeToken ( final JwtClaims claims , final OAuthRegisteredService registeredService , final AccessToken accessToken ) { LOGGER . debug ( "Received claims for the id token [{}] as [{}]" , accessToken , claims ) ; val idTokenResult = getConfigurationContext ( ) . getIdTokenSigningAndEncryptionService ( ) . encode ( registeredService , claims ) ; accessToken . setIdToken ( idTokenResult ) ; LOGGER . debug ( "Updating access token [{}] in ticket registry with ID token [{}]" , accessToken . getId ( ) , idTokenResult ) ; getConfigurationContext ( ) . getTicketRegistry ( ) . updateTicket ( accessToken ) ; return idTokenResult ; } | Encode and finalize token . |
18,148 | public Map < String , Object > releasePrincipalAttributes ( final String username , final String password , final String service ) { val selectedService = this . serviceFactory . createService ( service ) ; val registeredService = this . servicesManager . findServiceBy ( selectedService ) ; val credential = new UsernamePasswordCredential ( username , password ) ; val result = this . authenticationSystemSupport . handleAndFinalizeSingleAuthenticationTransaction ( selectedService , credential ) ; val authentication = result . getAuthentication ( ) ; val principal = authentication . getPrincipal ( ) ; val attributesToRelease = registeredService . getAttributeReleasePolicy ( ) . getAttributes ( principal , selectedService , registeredService ) ; val builder = DefaultAuthenticationBuilder . of ( principal , this . principalFactory , attributesToRelease , selectedService , registeredService , authentication ) ; val finalAuthentication = builder . build ( ) ; val assertion = new DefaultAssertionBuilder ( finalAuthentication ) . with ( selectedService ) . with ( CollectionUtils . wrap ( finalAuthentication ) ) . build ( ) ; val resValidation = new LinkedHashMap < String , Object > ( ) ; resValidation . put ( CasViewConstants . MODEL_ATTRIBUTE_NAME_ASSERTION , assertion ) ; resValidation . put ( CasViewConstants . MODEL_ATTRIBUTE_NAME_SERVICE , selectedService ) ; resValidation . put ( "registeredService" , registeredService ) ; return resValidation ; } | Release principal attributes map . |
18,149 | private void setResponseHeader ( final RequestContext context ) { val credential = WebUtils . getCredential ( context ) ; if ( credential == null ) { LOGGER . debug ( "No credential was provided. No response header set." ) ; return ; } val response = WebUtils . getHttpServletResponseFromExternalWebflowContext ( context ) ; val spnegoCredentials = ( SpnegoCredential ) credential ; val nextToken = spnegoCredentials . getNextToken ( ) ; if ( nextToken != null ) { LOGGER . debug ( "Obtained output token: [{}]" , new String ( nextToken , Charset . defaultCharset ( ) ) ) ; response . setHeader ( SpnegoConstants . HEADER_AUTHENTICATE , ( this . ntlm ? SpnegoConstants . NTLM : SpnegoConstants . NEGOTIATE ) + ' ' + EncodingUtils . encodeBase64 ( nextToken ) ) ; } else { LOGGER . debug ( "Unable to obtain the output token required." ) ; } if ( spnegoCredentials . getPrincipal ( ) == null && this . send401OnAuthenticationFailure ) { LOGGER . debug ( "Setting HTTP Status to 401" ) ; response . setStatus ( HttpServletResponse . SC_UNAUTHORIZED ) ; } } | Sets the response header based on the retrieved token . |
18,150 | protected String encryptResolvedUsername ( final Principal principal , final Service service , final RegisteredService registeredService , final String username ) { val applicationContext = ApplicationContextProvider . getApplicationContext ( ) ; val cipher = applicationContext . getBean ( "registeredServiceCipherExecutor" , RegisteredServiceCipherExecutor . class ) ; return cipher . encode ( username , Optional . of ( registeredService ) ) ; } | Encrypt resolved username . |
18,151 | public List < ConfigurationMetadataSearchResult > search ( final String name ) { val allProps = repository . getRepository ( ) . getAllProperties ( ) ; if ( StringUtils . isNotBlank ( name ) && RegexUtils . isValidRegex ( name ) ) { val names = StreamSupport . stream ( RelaxedPropertyNames . forCamelCase ( name ) . spliterator ( ) , false ) . map ( Object :: toString ) . collect ( Collectors . joining ( "|" ) ) ; val pattern = RegexUtils . createPattern ( names ) ; return allProps . entrySet ( ) . stream ( ) . filter ( propEntry -> RegexUtils . find ( pattern , propEntry . getKey ( ) ) ) . map ( propEntry -> new ConfigurationMetadataSearchResult ( propEntry . getValue ( ) , repository ) ) . sorted ( ) . collect ( Collectors . toList ( ) ) ; } return new ArrayList < > ( ) ; } | Search for property . |
18,152 | private static void setInResponseToForSamlResponseIfNeeded ( final Service service , final Response samlResponse ) { if ( service instanceof SamlService ) { val samlService = ( SamlService ) service ; val requestId = samlService . getRequestId ( ) ; if ( StringUtils . isNotBlank ( requestId ) ) { samlResponse . setInResponseTo ( requestId ) ; } } } | Sets in response to for saml 1 response . |
18,153 | public AuthenticationStatement newAuthenticationStatement ( final ZonedDateTime authenticationDate , final Collection < Object > authenticationMethod , final String subjectId ) { val authnStatement = newSamlObject ( AuthenticationStatement . class ) ; authnStatement . setAuthenticationInstant ( DateTimeUtils . dateTimeOf ( authenticationDate ) ) ; authnStatement . setAuthenticationMethod ( authenticationMethod != null && ! authenticationMethod . isEmpty ( ) ? authenticationMethod . iterator ( ) . next ( ) . toString ( ) : SamlAuthenticationMetaDataPopulator . AUTHN_METHOD_UNSPECIFIED ) ; authnStatement . setSubject ( newSubject ( subjectId ) ) ; return authnStatement ; } | New authentication statement . |
18,154 | public Subject newSubject ( final String identifier , final String confirmationMethod ) { val confirmation = newSamlObject ( SubjectConfirmation . class ) ; val method = newSamlObject ( ConfirmationMethod . class ) ; method . setConfirmationMethod ( confirmationMethod ) ; confirmation . getConfirmationMethods ( ) . add ( method ) ; val nameIdentifier = newSamlObject ( NameIdentifier . class ) ; nameIdentifier . setValue ( identifier ) ; val subject = newSamlObject ( Subject . class ) ; subject . setNameIdentifier ( nameIdentifier ) ; subject . setSubjectConfirmation ( confirmation ) ; return subject ; } | New subject element with given confirmation method . |
18,155 | public void addAttributeValuesToSaml1Attribute ( final String attributeName , final Object attributeValue , final List < XMLObject > attributeList ) { addAttributeValuesToSamlAttribute ( attributeName , attributeValue , StringUtils . EMPTY , attributeList , AttributeValue . DEFAULT_ELEMENT_NAME ) ; } | Add saml1 attribute values for attribute . |
18,156 | public static Response getPostResponse ( final String url , final Map < String , String > attributes ) { return new DefaultResponse ( ResponseType . POST , url , attributes ) ; } | Gets the post response . |
18,157 | public static Response getHeaderResponse ( final String url , final Map < String , String > attributes ) { return new DefaultResponse ( ResponseType . HEADER , url , attributes ) ; } | Gets header response . |
18,158 | public static Response getRedirectResponse ( final String url , final Map < String , String > parameters ) { val builder = new StringBuilder ( parameters . size ( ) * RESPONSE_INITIAL_CAPACITY ) ; val sanitizedUrl = sanitizeUrl ( url ) ; LOGGER . debug ( "Sanitized URL for redirect response is [{}]" , sanitizedUrl ) ; val fragmentSplit = Splitter . on ( "#" ) . splitToList ( sanitizedUrl ) ; builder . append ( fragmentSplit . get ( 0 ) ) ; val params = parameters . entrySet ( ) . stream ( ) . filter ( entry -> entry . getValue ( ) != null ) . map ( entry -> { try { return String . join ( "=" , entry . getKey ( ) , EncodingUtils . urlEncode ( entry . getValue ( ) ) ) ; } catch ( final Exception e ) { return String . join ( "=" , entry . getKey ( ) , entry . getValue ( ) ) ; } } ) . collect ( Collectors . joining ( "&" ) ) ; if ( ! ( params == null || params . isEmpty ( ) ) ) { builder . append ( url . contains ( "?" ) ? "&" : "?" ) ; builder . append ( params ) ; } if ( fragmentSplit . size ( ) > 1 ) { builder . append ( '#' ) ; builder . append ( fragmentSplit . get ( 1 ) ) ; } val urlRedirect = builder . toString ( ) ; LOGGER . debug ( "Final redirect response is [{}]" , urlRedirect ) ; return new DefaultResponse ( ResponseType . REDIRECT , urlRedirect , parameters ) ; } | Gets the redirect response . |
18,159 | private static String sanitizeUrl ( final String url ) { val m = NON_PRINTABLE . matcher ( url ) ; val sb = new StringBuffer ( url . length ( ) ) ; var hasNonPrintable = false ; while ( m . find ( ) ) { m . appendReplacement ( sb , " " ) ; hasNonPrintable = true ; } m . appendTail ( sb ) ; if ( hasNonPrintable ) { LOGGER . warn ( "The following redirect URL has been sanitized and may be sign of attack:\n[{}]" , url ) ; } return sb . toString ( ) ; } | Sanitize a URL provided by a relying party by normalizing non - printable ASCII character sequences into spaces . This functionality protects against CRLF attacks and other similar attacks using invisible characters that could be abused to trick user agents . |
18,160 | @ GetMapping ( path = SamlIdPConstants . ENDPOINT_IDP_METADATA ) public void generateMetadataForIdp ( final HttpServletResponse response ) throws IOException { this . metadataAndCertificatesGenerationService . generate ( ) ; val md = this . samlIdPMetadataLocator . getMetadata ( ) . getInputStream ( ) ; val contents = IOUtils . toString ( md , StandardCharsets . UTF_8 ) ; response . setContentType ( CONTENT_TYPE ) ; response . setStatus ( HttpServletResponse . SC_OK ) ; try ( val writer = response . getWriter ( ) ) { LOGGER . debug ( "Producing metadata for the response" ) ; writer . write ( contents ) ; writer . flush ( ) ; } } | Displays the identity provider metadata . Checks to make sure metadata exists and if not generates it first . |
18,161 | public ConfigurationMetadataProperty createConfigurationProperty ( final FieldDeclaration fieldDecl , final String propName ) { val variable = fieldDecl . getVariables ( ) . get ( 0 ) ; val name = StreamSupport . stream ( RelaxedPropertyNames . forCamelCase ( variable . getNameAsString ( ) ) . spliterator ( ) , false ) . map ( Object :: toString ) . findFirst ( ) . orElseGet ( variable :: getNameAsString ) ; val indexedGroup = propName . concat ( indexNameWithBrackets ? "[]" : StringUtils . EMPTY ) ; val indexedName = indexedGroup . concat ( "." ) . concat ( name ) ; val prop = new ConfigurationMetadataProperty ( ) ; if ( fieldDecl . getJavadoc ( ) . isPresent ( ) ) { val description = fieldDecl . getJavadoc ( ) . get ( ) . getDescription ( ) . toText ( ) ; prop . setDescription ( description ) ; prop . setShortDescription ( StringUtils . substringBefore ( description , "." ) ) ; } else { LOGGER . error ( "No Javadoc found for field [{}]" , indexedName ) ; } prop . setName ( indexedName ) ; prop . setId ( indexedName ) ; val elementType = fieldDecl . getElementType ( ) . asString ( ) ; if ( elementType . equals ( String . class . getSimpleName ( ) ) || elementType . equals ( Integer . class . getSimpleName ( ) ) || elementType . equals ( Long . class . getSimpleName ( ) ) || elementType . equals ( Double . class . getSimpleName ( ) ) || elementType . equals ( Float . class . getSimpleName ( ) ) ) { prop . setType ( "java.lang." + elementType ) ; } else { prop . setType ( elementType ) ; } val initializer = variable . getInitializer ( ) ; if ( initializer . isPresent ( ) ) { val exp = initializer . get ( ) ; if ( exp instanceof LiteralStringValueExpr ) { prop . setDefaultValue ( ( ( LiteralStringValueExpr ) exp ) . getValue ( ) ) ; } else if ( exp instanceof BooleanLiteralExpr ) { prop . setDefaultValue ( ( ( BooleanLiteralExpr ) exp ) . getValue ( ) ) ; } } properties . add ( prop ) ; val grp = new ConfigurationMetadataProperty ( ) ; grp . setId ( indexedGroup ) ; grp . setName ( indexedGroup ) ; grp . setType ( parentClass ) ; groups . add ( grp ) ; return prop ; } | Create configuration property . |
18,162 | @ ReadOperation ( produces = MediaType . TEXT_PLAIN_VALUE ) public String fetchPublicKey ( final String service ) throws Exception { val factory = KeyFactory . getInstance ( "RSA" ) ; var signingKey = tokenCipherExecutor . getSigningKey ( ) ; if ( StringUtils . isNotBlank ( service ) ) { val registeredService = this . servicesManager . findServiceBy ( service ) ; RegisteredServiceAccessStrategyUtils . ensureServiceAccessIsAllowed ( registeredService ) ; val serviceCipher = new RegisteredServiceJwtTicketCipherExecutor ( ) ; if ( serviceCipher . supports ( registeredService ) ) { val cipher = serviceCipher . getTokenTicketCipherExecutorForService ( registeredService ) ; if ( cipher . isEnabled ( ) ) { signingKey = cipher . getSigningKey ( ) ; } } } if ( signingKey instanceof RSAPrivateCrtKey ) { val rsaSigningKey = ( RSAPrivateCrtKey ) signingKey ; val publicKey = factory . generatePublic ( new RSAPublicKeySpec ( rsaSigningKey . getModulus ( ) , rsaSigningKey . getPublicExponent ( ) ) ) ; return EncodingUtils . encodeBase64 ( publicKey . getEncoded ( ) ) ; } return null ; } | Fetch public key . |
18,163 | public Map < String , Object > getCachedMetadataObject ( final String serviceId , final String entityId ) { try { val registeredService = findRegisteredService ( serviceId ) ; val issuer = StringUtils . defaultIfBlank ( entityId , registeredService . getServiceId ( ) ) ; val criteriaSet = new CriteriaSet ( ) ; criteriaSet . add ( new EntityIdCriterion ( issuer ) ) ; criteriaSet . add ( new EntityRoleCriterion ( SPSSODescriptor . DEFAULT_ELEMENT_NAME ) ) ; val metadataResolver = cachingMetadataResolver . resolve ( registeredService , criteriaSet ) ; val iteration = metadataResolver . resolve ( criteriaSet ) . spliterator ( ) ; return StreamSupport . stream ( iteration , false ) . map ( entity -> Pair . of ( entity . getEntityID ( ) , SamlUtils . transformSamlObject ( openSamlConfigBean , entity ) . toString ( ) ) ) . collect ( Collectors . toMap ( Pair :: getLeft , Pair :: getRight ) ) ; } catch ( final Exception e ) { LOGGER . error ( e . getMessage ( ) , e ) ; return CollectionUtils . wrap ( "error" , e . getMessage ( ) ) ; } } | Gets cached metadata object . |
18,164 | public static Resource prepareClasspathResourceIfNeeded ( final Resource resource ) { if ( resource == null ) { LOGGER . debug ( "No resource defined to prepare. Returning null" ) ; return null ; } return prepareClasspathResourceIfNeeded ( resource , false , resource . getFilename ( ) ) ; } | Prepare classpath resource if needed file . |
18,165 | public static Resource prepareClasspathResourceIfNeeded ( final Resource resource , final boolean isDirectory , final String containsName ) { LOGGER . trace ( "Preparing possible classpath resource [{}]" , resource ) ; if ( resource == null ) { LOGGER . debug ( "No resource defined to prepare. Returning null" ) ; return null ; } if ( org . springframework . util . ResourceUtils . isFileURL ( resource . getURL ( ) ) ) { return resource ; } val url = org . springframework . util . ResourceUtils . extractArchiveURL ( resource . getURL ( ) ) ; val file = org . springframework . util . ResourceUtils . getFile ( url ) ; val casDirectory = new File ( FileUtils . getTempDirectory ( ) , "cas" ) ; val destination = new File ( casDirectory , resource . getFilename ( ) ) ; if ( isDirectory ) { LOGGER . trace ( "Creating resource directory [{}]" , destination ) ; FileUtils . forceMkdir ( destination ) ; FileUtils . cleanDirectory ( destination ) ; } else if ( destination . exists ( ) ) { LOGGER . trace ( "Deleting resource directory [{}]" , destination ) ; FileUtils . forceDelete ( destination ) ; } LOGGER . trace ( "Processing file [{}]" , file ) ; try ( val jFile = new JarFile ( file ) ) { val e = jFile . entries ( ) ; while ( e . hasMoreElements ( ) ) { val entry = e . nextElement ( ) ; val name = entry . getName ( ) ; LOGGER . trace ( "Comparing [{}] against [{}] and pattern [{}]" , name , resource . getFilename ( ) , containsName ) ; if ( name . contains ( resource . getFilename ( ) ) && RegexUtils . find ( containsName , name ) ) { try ( val stream = jFile . getInputStream ( entry ) ) { var copyDestination = destination ; if ( isDirectory ) { val entryFileName = new File ( name ) ; copyDestination = new File ( destination , entryFileName . getName ( ) ) ; } LOGGER . trace ( "Copying resource entry [{}] to [{}]" , name , copyDestination ) ; try ( val writer = Files . newBufferedWriter ( copyDestination . toPath ( ) , StandardCharsets . UTF_8 ) ) { IOUtils . copy ( stream , writer , StandardCharsets . UTF_8 ) ; } } } } } return new FileSystemResource ( destination ) ; } | If the provided resource is a classpath resource running inside an embedded container and if the container is running in a non - exploded form classpath resources become non - accessible . So this method will attempt to move resources out of classpath and onto a physical location outside the context typically in the cas directory of the temp system folder . |
18,166 | public static InputStreamResource buildInputStreamResourceFrom ( final String value , final String description ) { val reader = new StringReader ( value ) ; val is = new ReaderInputStream ( reader , StandardCharsets . UTF_8 ) ; return new InputStreamResource ( is , description ) ; } | Build input stream resource from string value . |
18,167 | public Set < AuditActionContext > getAuditLog ( ) { val sinceDate = LocalDate . now ( ) . minusDays ( casProperties . getAudit ( ) . getNumberOfDaysInHistory ( ) ) ; return this . auditTrailManager . getAuditRecordsSince ( sinceDate ) ; } | Gets audit log . |
18,168 | public boolean isValid ( final String expectedAudience , final String expectedIssuer , final long timeDrift ) { if ( ! this . audience . equalsIgnoreCase ( expectedAudience ) ) { LOGGER . warn ( "Audience [{}] is invalid where the expected audience should be [{}]" , this . audience , expectedAudience ) ; return false ; } if ( ! this . issuer . equalsIgnoreCase ( expectedIssuer ) ) { LOGGER . warn ( "Issuer [{}] is invalid since the expected issuer should be [{}]" , this . issuer , expectedIssuer ) ; return false ; } val retrievedOnTimeDrift = this . getRetrievedOn ( ) . minus ( timeDrift , ChronoUnit . MILLIS ) ; if ( this . issuedOn . isBefore ( retrievedOnTimeDrift ) ) { LOGGER . warn ( "Ticket is issued before the allowed drift. Issued on [{}] while allowed drift is [{}]" , this . issuedOn , retrievedOnTimeDrift ) ; return false ; } val retrievedOnTimeAfterDrift = this . retrievedOn . plus ( timeDrift , ChronoUnit . MILLIS ) ; if ( this . issuedOn . isAfter ( retrievedOnTimeAfterDrift ) ) { LOGGER . warn ( "Ticket is issued after the allowed drift. Issued on [{}] while allowed drift is [{}]" , this . issuedOn , retrievedOnTimeAfterDrift ) ; return false ; } if ( this . retrievedOn . isAfter ( this . notOnOrAfter ) ) { LOGGER . warn ( "Ticket is too late because it's retrieved on [{}] which is after [{}]." , this . retrievedOn , this . notOnOrAfter ) ; return false ; } LOGGER . debug ( "WsFed Credential is validated for [{}] and [{}]." , expectedAudience , expectedIssuer ) ; return true ; } | isValid validates the credential . |
18,169 | private Event verify ( final RequestContext context , final Credential credential , final MessageContext messageContext ) { val res = repository . verify ( context , credential ) ; WebUtils . putPrincipal ( context , res . getPrincipal ( ) ) ; WebUtils . putAcceptableUsagePolicyStatusIntoFlowScope ( context , res ) ; val eventFactorySupport = new EventFactorySupport ( ) ; return res . isAccepted ( ) ? eventFactorySupport . event ( this , CasWebflowConstants . TRANSITION_ID_AUP_ACCEPTED ) : eventFactorySupport . event ( this , CasWebflowConstants . TRANSITION_ID_AUP_MUST_ACCEPT ) ; } | Verify whether the policy is accepted . |
18,170 | protected void validateIdTokenIfAny ( final AccessToken accessToken , final CommonProfile profile ) throws MalformedClaimException { if ( StringUtils . isNotBlank ( accessToken . getIdToken ( ) ) ) { val idTokenResult = idTokenSigningAndEncryptionService . validate ( accessToken . getIdToken ( ) ) ; profile . setId ( idTokenResult . getSubject ( ) ) ; profile . addAttributes ( idTokenResult . getClaimsMap ( ) ) ; } } | Validate id token if any . |
18,171 | public static List < String > canonicalizeSecurityQuestions ( final Map < String , String > questionMap ) { val keys = new ArrayList < String > ( questionMap . keySet ( ) ) ; keys . sort ( String . CASE_INSENSITIVE_ORDER ) ; return keys ; } | Orders security questions consistently . |
18,172 | public MapConfig buildMapConfig ( final BaseHazelcastProperties hz , final String mapName , final long timeoutSeconds ) { val cluster = hz . getCluster ( ) ; val evictionPolicy = EvictionPolicy . valueOf ( cluster . getEvictionPolicy ( ) ) ; LOGGER . trace ( "Creating Hazelcast map configuration for [{}] with idle timeoutSeconds [{}] second(s)" , mapName , timeoutSeconds ) ; val maxSizeConfig = new MaxSizeConfig ( ) . setMaxSizePolicy ( MaxSizeConfig . MaxSizePolicy . valueOf ( cluster . getMaxSizePolicy ( ) ) ) . setSize ( cluster . getMaxHeapSizePercentage ( ) ) ; val mergePolicyConfig = new MergePolicyConfig ( ) ; if ( StringUtils . hasText ( cluster . getMapMergePolicy ( ) ) ) { mergePolicyConfig . setPolicy ( cluster . getMapMergePolicy ( ) ) ; } return new MapConfig ( ) . setName ( mapName ) . setMergePolicyConfig ( mergePolicyConfig ) . setMaxIdleSeconds ( ( int ) timeoutSeconds ) . setBackupCount ( cluster . getBackupCount ( ) ) . setAsyncBackupCount ( cluster . getAsyncBackupCount ( ) ) . setEvictionPolicy ( evictionPolicy ) . setMaxSizeConfig ( maxSizeConfig ) ; } | Build map config map config . |
18,173 | protected static Pair < AuthnRequest , MessageContext > buildAuthenticationContextPair ( final HttpServletRequest request , final AuthnRequest authnRequest ) { val messageContext = bindRelayStateParameter ( request ) ; return Pair . of ( authnRequest , messageContext ) ; } | Build authentication context pair pair . |
18,174 | @ GetMapping ( path = SamlIdPConstants . ENDPOINT_SAML2_SSO_PROFILE_POST_CALLBACK ) protected void handleCallbackProfileRequest ( final HttpServletResponse response , final HttpServletRequest request ) throws Exception { LOGGER . info ( "Received SAML callback profile request [{}]" , request . getRequestURI ( ) ) ; val authnRequest = retrieveSamlAuthenticationRequestFromHttpRequest ( request ) ; if ( authnRequest == null ) { LOGGER . error ( "Can not validate the request because the original Authn request can not be found." ) ; response . setStatus ( HttpServletResponse . SC_FORBIDDEN ) ; return ; } val ticket = CommonUtils . safeGetParameter ( request , CasProtocolConstants . PARAMETER_TICKET ) ; if ( StringUtils . isBlank ( ticket ) ) { LOGGER . error ( "Can not validate the request because no [{}] is provided via the request" , CasProtocolConstants . PARAMETER_TICKET ) ; response . setStatus ( HttpServletResponse . SC_FORBIDDEN ) ; return ; } val authenticationContext = buildAuthenticationContextPair ( request , authnRequest ) ; val assertion = validateRequestAndBuildCasAssertion ( response , request , authenticationContext ) ; val binding = determineProfileBinding ( authenticationContext , assertion ) ; buildSamlResponse ( response , request , authenticationContext , assertion , binding ) ; } | Handle callback profile request . |
18,175 | protected String determineProfileBinding ( final Pair < AuthnRequest , MessageContext > authenticationContext , final Assertion assertion ) { val authnRequest = authenticationContext . getKey ( ) ; val pair = getRegisteredServiceAndFacade ( authnRequest ) ; val facade = pair . getValue ( ) ; val binding = StringUtils . defaultIfBlank ( authnRequest . getProtocolBinding ( ) , SAMLConstants . SAML2_POST_BINDING_URI ) ; LOGGER . debug ( "Determined authentication request binding is [{}], issued by [{}]" , binding , authnRequest . getIssuer ( ) . getValue ( ) ) ; val entityId = facade . getEntityId ( ) ; LOGGER . debug ( "Checking metadata for [{}] to see if binding [{}] is supported" , entityId , binding ) ; val svc = facade . getAssertionConsumerService ( binding ) ; LOGGER . debug ( "Binding [{}] is supported by [{}]" , svc . getBinding ( ) , entityId ) ; return binding ; } | Determine profile binding . |
18,176 | protected BigDecimal calculateScore ( final HttpServletRequest request , final Authentication authentication , final RegisteredService service , final Collection < ? extends CasEvent > events ) { return HIGHEST_RISK_SCORE ; } | Calculate score authentication risk score . |
18,177 | protected Collection < ? extends CasEvent > getCasTicketGrantingTicketCreatedEventsFor ( final String principal ) { val type = CasTicketGrantingTicketCreatedEvent . class . getName ( ) ; LOGGER . debug ( "Retrieving events of type [{}] for [{}]" , type , principal ) ; val date = ZonedDateTime . now ( ZoneOffset . UTC ) . minusDays ( casProperties . getAuthn ( ) . getAdaptive ( ) . getRisk ( ) . getDaysInRecentHistory ( ) ) ; return casEventRepository . getEventsOfTypeForPrincipal ( type , principal , date ) ; } | Gets cas ticket granting ticket created events . |
18,178 | protected BigDecimal calculateScoreBasedOnEventsCount ( final Authentication authentication , final Collection < ? extends CasEvent > events , final long count ) { if ( count == events . size ( ) ) { LOGGER . debug ( "Principal [{}] is assigned to the lowest risk score with attempted count of [{}]" , authentication . getPrincipal ( ) , count ) ; return LOWEST_RISK_SCORE ; } return getFinalAveragedScore ( count , events . size ( ) ) ; } | Calculate score based on events count big decimal . |
18,179 | protected BigDecimal getFinalAveragedScore ( final long eventCount , final long total ) { val score = BigDecimal . valueOf ( eventCount ) . divide ( BigDecimal . valueOf ( total ) , 2 , RoundingMode . HALF_UP ) ; return HIGHEST_RISK_SCORE . subtract ( score ) ; } | Gets final averaged score . |
18,180 | public static boolean isExpired ( final X509CRL crl , final ZonedDateTime reference ) { return reference . isAfter ( DateTimeUtils . zonedDateTimeOf ( crl . getNextUpdate ( ) ) ) ; } | Determines whether the given CRL is expired by comparing the nextUpdate field with a given date . |
18,181 | public static X509Certificate readCertificate ( final InputStreamSource resource ) { try ( val in = resource . getInputStream ( ) ) { return CertUtil . readCertificate ( in ) ; } catch ( final IOException e ) { throw new IllegalArgumentException ( "Error reading certificate " + resource , e ) ; } } | Read certificate . |
18,182 | protected void buildEcpFaultResponse ( final HttpServletResponse response , final HttpServletRequest request , final Pair < RequestAbstractType , String > authenticationContext ) { request . setAttribute ( SamlIdPConstants . REQUEST_ATTRIBUTE_ERROR , authenticationContext . getValue ( ) ) ; getSamlProfileHandlerConfigurationContext ( ) . getSamlFaultResponseBuilder ( ) . build ( authenticationContext . getKey ( ) , request , response , null , null , null , SAMLConstants . SAML2_PAOS_BINDING_URI , null ) ; } | Build ecp fault response . |
18,183 | protected Authentication authenticateEcpRequest ( final Credential credential , final Pair < AuthnRequest , MessageContext > authnRequest ) { val issuer = SamlIdPUtils . getIssuerFromSamlObject ( authnRequest . getKey ( ) ) ; LOGGER . debug ( "Located issuer [{}] from request prior to authenticating [{}]" , issuer , credential . getId ( ) ) ; val service = getSamlProfileHandlerConfigurationContext ( ) . getWebApplicationServiceFactory ( ) . createService ( issuer ) ; LOGGER . debug ( "Executing authentication request for service [{}] on behalf of credential id [{}]" , service , credential . getId ( ) ) ; val authenticationResult = getSamlProfileHandlerConfigurationContext ( ) . getAuthenticationSystemSupport ( ) . handleAndFinalizeSingleAuthenticationTransaction ( service , credential ) ; return authenticationResult . getAuthentication ( ) ; } | Authenticate ecp request . |
18,184 | public Collection < Map < String , Object > > consentDecisions ( final String principal ) { val result = new HashSet < Map < String , Object > > ( ) ; LOGGER . debug ( "Fetching consent decisions for principal [{}]" , principal ) ; val consentDecisions = this . consentRepository . findConsentDecisions ( principal ) ; LOGGER . debug ( "Resolved consent decisions for principal [{}]: [{}]" , principal , consentDecisions ) ; consentDecisions . forEach ( d -> { val map = new HashMap < String , Object > ( ) ; map . put ( "decision" , d ) ; map . put ( "attributes" , this . consentEngine . resolveConsentableAttributesFrom ( d ) ) ; result . add ( map ) ; } ) ; return result ; } | Consent decisions collection . |
18,185 | public boolean revokeConsents ( final String principal , final long decisionId ) { LOGGER . debug ( "Deleting consent decisions for principal [{}]." , principal ) ; return this . consentRepository . deleteConsentDecision ( decisionId , principal ) ; } | Revoke consents . |
18,186 | public void setValues ( final Set < String > values ) { getValues ( ) . clear ( ) ; if ( values == null ) { return ; } getValues ( ) . addAll ( values ) ; } | Sets values . |
18,187 | public static Map < String , List < Object > > convertAttributeValuesToMultiValuedObjects ( final Map < String , Object > attributes ) { val entries = attributes . entrySet ( ) ; return entries . stream ( ) . collect ( Collectors . toMap ( Map . Entry :: getKey , entry -> { val value = entry . getValue ( ) ; return CollectionUtils . toCollection ( value , ArrayList . class ) ; } ) ) ; } | Convert attribute values to multi valued objects . |
18,188 | public static Map < String , List < Object > > retrieveAttributesFromAttributeRepository ( final IPersonAttributeDao attributeRepository , final String principalId , final Set < String > activeAttributeRepositoryIdentifiers ) { var filter = IPersonAttributeDaoFilter . alwaysChoose ( ) ; if ( activeAttributeRepositoryIdentifiers != null && ! activeAttributeRepositoryIdentifiers . isEmpty ( ) ) { val repoIdsArray = activeAttributeRepositoryIdentifiers . toArray ( ArrayUtils . EMPTY_STRING_ARRAY ) ; filter = dao -> Arrays . stream ( dao . getId ( ) ) . anyMatch ( daoId -> daoId . equalsIgnoreCase ( IPersonAttributeDao . WILDCARD ) || StringUtils . equalsAnyIgnoreCase ( daoId , repoIdsArray ) || StringUtils . equalsAnyIgnoreCase ( IPersonAttributeDao . WILDCARD , repoIdsArray ) ) ; } val attrs = attributeRepository . getPerson ( principalId , filter ) ; if ( attrs == null ) { return new HashMap < > ( 0 ) ; } return attrs . getAttributes ( ) ; } | Retrieve attributes from attribute repository and return map . |
18,189 | public static IAttributeMerger getAttributeMerger ( final String mergingPolicy ) { switch ( mergingPolicy . toLowerCase ( ) ) { case "multivalued" : case "multi_valued" : case "combine" : return new MultivaluedAttributeMerger ( ) ; case "add" : return new NoncollidingAttributeAdder ( ) ; case "replace" : case "overwrite" : case "override" : return new ReplacingAttributeAdder ( ) ; default : return new BaseAdditiveAttributeMerger ( ) { protected Map < String , List < Object > > mergePersonAttributes ( final Map < String , List < Object > > toModify , final Map < String , List < Object > > toConsider ) { return new LinkedHashMap < > ( toModify ) ; } } ; } } | Gets attribute merger . |
18,190 | public static Map < String , List < Object > > mergeAttributes ( final Map < String , List < Object > > currentAttributes , final Map < String , List < Object > > attributesToMerge ) { val merger = new MultivaluedAttributeMerger ( ) ; val toModify = currentAttributes . entrySet ( ) . stream ( ) . map ( entry -> Pair . of ( entry . getKey ( ) , CollectionUtils . toCollection ( entry . getValue ( ) , ArrayList . class ) ) ) . collect ( Collectors . toMap ( Pair :: getKey , Pair :: getValue ) ) ; val toMerge = attributesToMerge . entrySet ( ) . stream ( ) . map ( entry -> Pair . of ( entry . getKey ( ) , CollectionUtils . toCollection ( entry . getValue ( ) , ArrayList . class ) ) ) . collect ( Collectors . toMap ( Pair :: getKey , Pair :: getValue ) ) ; LOGGER . trace ( "Merging current attributes [{}] with [{}]" , toModify , toMerge ) ; val results = merger . mergeAttributes ( ( Map ) toModify , ( Map ) toMerge ) ; LOGGER . debug ( "Merged attributes with the final result as [{}]" , results ) ; return results ; } | Merge attributes map . |
18,191 | public static Map < String , Object > transformPrincipalAttributesListIntoMap ( final List < String > list ) { val map = transformPrincipalAttributesListIntoMultiMap ( list ) ; return CollectionUtils . wrap ( map ) ; } | Transform principal attributes list into map map . |
18,192 | public static Predicate < Credential > newCredentialSelectionPredicate ( final String selectionCriteria ) { try { if ( StringUtils . isBlank ( selectionCriteria ) ) { return credential -> true ; } if ( selectionCriteria . endsWith ( ".groovy" ) ) { val loader = new DefaultResourceLoader ( ) ; val resource = loader . getResource ( selectionCriteria ) ; val script = IOUtils . toString ( resource . getInputStream ( ) , StandardCharsets . UTF_8 ) ; val clz = AccessController . doPrivileged ( ( PrivilegedAction < Class < Predicate > > ) ( ) -> { val classLoader = new GroovyClassLoader ( Beans . class . getClassLoader ( ) , new CompilerConfiguration ( ) , true ) ; return classLoader . parseClass ( script ) ; } ) ; return clz . getDeclaredConstructor ( ) . newInstance ( ) ; } val predicateClazz = ClassUtils . getClass ( selectionCriteria ) ; return ( Predicate < org . apereo . cas . authentication . Credential > ) predicateClazz . getDeclaredConstructor ( ) . newInstance ( ) ; } catch ( final Exception e ) { val predicate = Pattern . compile ( selectionCriteria ) . asPredicate ( ) ; return credential -> predicate . test ( credential . getId ( ) ) ; } } | Gets credential selection predicate . |
18,193 | public static AuthenticationPasswordPolicyHandlingStrategy newPasswordPolicyHandlingStrategy ( final PasswordPolicyProperties properties ) { if ( properties . getStrategy ( ) == PasswordPolicyProperties . PasswordPolicyHandlingOptions . REJECT_RESULT_CODE ) { LOGGER . debug ( "Created password policy handling strategy based on blacklisted authentication result codes" ) ; return new RejectResultCodePasswordPolicyHandlingStrategy ( ) ; } val location = properties . getGroovy ( ) . getLocation ( ) ; if ( properties . getStrategy ( ) == PasswordPolicyProperties . PasswordPolicyHandlingOptions . GROOVY && location != null ) { LOGGER . debug ( "Created password policy handling strategy based on Groovy script [{}]" , location ) ; return new GroovyPasswordPolicyHandlingStrategy ( location ) ; } LOGGER . trace ( "Created default password policy handling strategy" ) ; return new DefaultPasswordPolicyHandlingStrategy ( ) ; } | New password policy handling strategy . |
18,194 | public static PrincipalResolver newPersonDirectoryPrincipalResolver ( final PrincipalFactory principalFactory , final IPersonAttributeDao attributeRepository , final PersonDirectoryPrincipalResolverProperties personDirectory ) { return new PersonDirectoryPrincipalResolver ( attributeRepository , principalFactory , personDirectory . isReturnNull ( ) , personDirectory . getPrincipalAttribute ( ) , personDirectory . isUseExistingPrincipalId ( ) , personDirectory . isAttributeResolutionEnabled ( ) , org . springframework . util . StringUtils . commaDelimitedListToSet ( personDirectory . getActiveAttributeRepositoryIds ( ) ) ) ; } | New person directory principal resolver . |
18,195 | public HazelcastInstance hazelcastInstance ( ) { val hzConfigResource = casProperties . getWebflow ( ) . getSession ( ) . getHzLocation ( ) ; val configUrl = hzConfigResource . getURL ( ) ; val config = new XmlConfigBuilder ( hzConfigResource . getInputStream ( ) ) . build ( ) ; config . setConfigurationUrl ( configUrl ) ; config . setInstanceName ( this . getClass ( ) . getSimpleName ( ) ) . setProperty ( "hazelcast.logging.type" , "slf4j" ) . setProperty ( "hazelcast.max.no.heartbeat.seconds" , "300" ) ; return Hazelcast . newHazelcastInstance ( config ) ; } | Hazelcast instance that is used by the spring session repository to broadcast session events . The name of this bean must be left untouched . |
18,196 | public void putPasswordResetToken ( final RequestContext requestContext , final String token ) { val flowScope = requestContext . getFlowScope ( ) ; flowScope . put ( FLOWSCOPE_PARAMETER_NAME_TOKEN , token ) ; } | Put password reset token . |
18,197 | public void putPasswordResetSecurityQuestions ( final RequestContext requestContext , final List < String > value ) { val flowScope = requestContext . getFlowScope ( ) ; flowScope . put ( "questions" , value ) ; } | Put password reset security questions . |
18,198 | public static List < String > getPasswordResetQuestions ( final RequestContext requestContext ) { val flowScope = requestContext . getFlowScope ( ) ; return flowScope . get ( "questions" , List . class ) ; } | Gets password reset questions . |
18,199 | public static void putPasswordResetSecurityQuestionsEnabled ( final RequestContext requestContext , final boolean value ) { val flowScope = requestContext . getFlowScope ( ) ; flowScope . put ( "questionsEnabled" , value ) ; } | Put password reset security questions enabled . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.