idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
17,600
public static SecureRandom getNativeInstance ( ) { try { return SecureRandom . getInstance ( NATIVE_NON_BLOCKING_ALGORITHM ) ; } catch ( final NoSuchAlgorithmException e ) { LOGGER . trace ( e . getMessage ( ) , e ) ; return new SecureRandom ( ) ; } }
Get strong enough SecureRandom instance and of the checked exception .
17,601
public static String generateSecureRandomId ( ) { val generator = getNativeInstance ( ) ; val charMappings = new char [ ] { 'a' , 'b' , 'c' , 'd' , 'e' , 'f' , 'g' , 'h' , 'i' , 'j' , 'k' , 'l' , 'm' , 'n' , 'o' , 'p' } ; val bytes = new byte [ SECURE_ID_BYTES_LENGTH ] ; generator . nextBytes ( bytes ) ; val chars = new char [ SECURE_ID_CHARS_LENGTH ] ; IntStream . range ( 0 , bytes . length ) . forEach ( i -> { val left = bytes [ i ] >> SECURE_ID_SHIFT_LENGTH & HEX_HIGH_BITS_BITWISE_FLAG ; val right = bytes [ i ] & HEX_HIGH_BITS_BITWISE_FLAG ; chars [ i * 2 ] = charMappings [ left ] ; chars [ i * 2 + 1 ] = charMappings [ right ] ; } ) ; return String . valueOf ( chars ) ; }
Generate secure random id string .
17,602
public boolean canPing ( ) { try { val connection = ( HttpURLConnection ) new URL ( this . swivelUrl ) . openConnection ( ) ; connection . setRequestMethod ( HttpMethod . GET . name ( ) ) ; connection . connect ( ) ; return connection . getResponseCode ( ) == HttpStatus . SC_OK ; } catch ( final Exception e ) { LOGGER . warn ( e . getMessage ( ) , e ) ; } return false ; }
Can ping provider?
17,603
protected void configureGitHubClient ( final Collection < BaseClient > properties ) { val github = pac4jProperties . getGithub ( ) ; if ( StringUtils . isNotBlank ( github . getId ( ) ) && StringUtils . isNotBlank ( github . getSecret ( ) ) ) { val client = new GitHubClient ( github . getId ( ) , github . getSecret ( ) ) ; configureClient ( client , github ) ; LOGGER . debug ( "Created client [{}] with identifier [{}]" , client . getName ( ) , client . getKey ( ) ) ; properties . add ( client ) ; } }
Configure github client .
17,604
protected void configureDropBoxClient ( final Collection < BaseClient > properties ) { val db = pac4jProperties . getDropbox ( ) ; if ( StringUtils . isNotBlank ( db . getId ( ) ) && StringUtils . isNotBlank ( db . getSecret ( ) ) ) { val client = new DropBoxClient ( db . getId ( ) , db . getSecret ( ) ) ; configureClient ( client , db ) ; LOGGER . debug ( "Created client [{}] with identifier [{}]" , client . getName ( ) , client . getKey ( ) ) ; properties . add ( client ) ; } }
Configure dropbox client .
17,605
protected void configureOrcidClient ( final Collection < BaseClient > properties ) { val db = pac4jProperties . getOrcid ( ) ; if ( StringUtils . isNotBlank ( db . getId ( ) ) && StringUtils . isNotBlank ( db . getSecret ( ) ) ) { val client = new OrcidClient ( db . getId ( ) , db . getSecret ( ) ) ; configureClient ( client , db ) ; LOGGER . debug ( "Created client [{}] with identifier [{}]" , client . getName ( ) , client . getKey ( ) ) ; properties . add ( client ) ; } }
Configure orcid client .
17,606
protected void configureWindowsLiveClient ( final Collection < BaseClient > properties ) { val live = pac4jProperties . getWindowsLive ( ) ; if ( StringUtils . isNotBlank ( live . getId ( ) ) && StringUtils . isNotBlank ( live . getSecret ( ) ) ) { val client = new WindowsLiveClient ( live . getId ( ) , live . getSecret ( ) ) ; configureClient ( client , live ) ; LOGGER . debug ( "Created client [{}] with identifier [{}]" , client . getName ( ) , client . getKey ( ) ) ; properties . add ( client ) ; } }
Configure windows live client .
17,607
protected void configureYahooClient ( final Collection < BaseClient > properties ) { val yahoo = pac4jProperties . getYahoo ( ) ; if ( StringUtils . isNotBlank ( yahoo . getId ( ) ) && StringUtils . isNotBlank ( yahoo . getSecret ( ) ) ) { val client = new YahooClient ( yahoo . getId ( ) , yahoo . getSecret ( ) ) ; configureClient ( client , yahoo ) ; LOGGER . debug ( "Created client [{}] with identifier [{}]" , client . getName ( ) , client . getKey ( ) ) ; properties . add ( client ) ; } }
Configure yahoo client .
17,608
protected void configureFoursquareClient ( final Collection < BaseClient > properties ) { val foursquare = pac4jProperties . getFoursquare ( ) ; if ( StringUtils . isNotBlank ( foursquare . getId ( ) ) && StringUtils . isNotBlank ( foursquare . getSecret ( ) ) ) { val client = new FoursquareClient ( foursquare . getId ( ) , foursquare . getSecret ( ) ) ; configureClient ( client , foursquare ) ; LOGGER . debug ( "Created client [{}] with identifier [{}]" , client . getName ( ) , client . getKey ( ) ) ; properties . add ( client ) ; } }
Configure foursquare client .
17,609
protected void configureGoogleClient ( final Collection < BaseClient > properties ) { val google = pac4jProperties . getGoogle ( ) ; val client = new Google2Client ( google . getId ( ) , google . getSecret ( ) ) ; if ( StringUtils . isNotBlank ( google . getId ( ) ) && StringUtils . isNotBlank ( google . getSecret ( ) ) ) { configureClient ( client , google ) ; if ( StringUtils . isNotBlank ( google . getScope ( ) ) ) { client . setScope ( Google2Client . Google2Scope . valueOf ( google . getScope ( ) . toUpperCase ( ) ) ) ; } LOGGER . debug ( "Created client [{}] with identifier [{}]" , client . getName ( ) , client . getKey ( ) ) ; properties . add ( client ) ; } }
Configure google client .
17,610
protected void configureFacebookClient ( final Collection < BaseClient > properties ) { val fb = pac4jProperties . getFacebook ( ) ; if ( StringUtils . isNotBlank ( fb . getId ( ) ) && StringUtils . isNotBlank ( fb . getSecret ( ) ) ) { val client = new FacebookClient ( fb . getId ( ) , fb . getSecret ( ) ) ; configureClient ( client , fb ) ; if ( StringUtils . isNotBlank ( fb . getScope ( ) ) ) { client . setScope ( fb . getScope ( ) ) ; } if ( StringUtils . isNotBlank ( fb . getFields ( ) ) ) { client . setFields ( fb . getFields ( ) ) ; } LOGGER . debug ( "Created client [{}] with identifier [{}]" , client . getName ( ) , client . getKey ( ) ) ; properties . add ( client ) ; } }
Configure facebook client .
17,611
protected void configureLinkedInClient ( final Collection < BaseClient > properties ) { val ln = pac4jProperties . getLinkedIn ( ) ; if ( StringUtils . isNotBlank ( ln . getId ( ) ) && StringUtils . isNotBlank ( ln . getSecret ( ) ) ) { val client = new LinkedIn2Client ( ln . getId ( ) , ln . getSecret ( ) ) ; configureClient ( client , ln ) ; if ( StringUtils . isNotBlank ( ln . getScope ( ) ) ) { client . setScope ( ln . getScope ( ) ) ; } if ( StringUtils . isNotBlank ( ln . getFields ( ) ) ) { client . setFields ( ln . getFields ( ) ) ; } LOGGER . debug ( "Created client [{}] with identifier [{}]" , client . getName ( ) , client . getKey ( ) ) ; properties . add ( client ) ; } }
Configure linked in client .
17,612
protected void configureHiOrgServerClient ( final Collection < BaseClient > properties ) { val hiOrgServer = pac4jProperties . getHiOrgServer ( ) ; if ( StringUtils . isNotBlank ( hiOrgServer . getId ( ) ) && StringUtils . isNotBlank ( hiOrgServer . getSecret ( ) ) ) { val client = new HiOrgServerClient ( hiOrgServer . getId ( ) , hiOrgServer . getSecret ( ) ) ; configureClient ( client , hiOrgServer ) ; if ( StringUtils . isNotBlank ( hiOrgServer . getScope ( ) ) ) { client . getConfiguration ( ) . setScope ( hiOrgServer . getScope ( ) ) ; } LOGGER . debug ( "Created client [{}] with identifier [{}]" , client . getName ( ) , client . getKey ( ) ) ; properties . add ( client ) ; } }
Configure HiOrg - Server client .
17,613
protected void configureTwitterClient ( final Collection < BaseClient > properties ) { val twitter = pac4jProperties . getTwitter ( ) ; if ( StringUtils . isNotBlank ( twitter . getId ( ) ) && StringUtils . isNotBlank ( twitter . getSecret ( ) ) ) { val client = new TwitterClient ( twitter . getId ( ) , twitter . getSecret ( ) , twitter . isIncludeEmail ( ) ) ; configureClient ( client , twitter ) ; LOGGER . debug ( "Created client [{}] with identifier [{}]" , client . getName ( ) , client . getKey ( ) ) ; properties . add ( client ) ; } }
Configure twitter client .
17,614
protected void configureWordPressClient ( final Collection < BaseClient > properties ) { val wp = pac4jProperties . getWordpress ( ) ; if ( StringUtils . isNotBlank ( wp . getId ( ) ) && StringUtils . isNotBlank ( wp . getSecret ( ) ) ) { val client = new WordPressClient ( wp . getId ( ) , wp . getSecret ( ) ) ; configureClient ( client , wp ) ; LOGGER . debug ( "Created client [{}] with identifier [{}]" , client . getName ( ) , client . getKey ( ) ) ; properties . add ( client ) ; } }
Configure wordpress client .
17,615
protected void configureBitBucketClient ( final Collection < BaseClient > properties ) { val bb = pac4jProperties . getBitbucket ( ) ; if ( StringUtils . isNotBlank ( bb . getId ( ) ) && StringUtils . isNotBlank ( bb . getSecret ( ) ) ) { val client = new BitbucketClient ( bb . getId ( ) , bb . getSecret ( ) ) ; configureClient ( client , bb ) ; LOGGER . debug ( "Created client [{}] with identifier [{}]" , client . getName ( ) , client . getKey ( ) ) ; properties . add ( client ) ; } }
Configure bitbucket client .
17,616
protected void configurePayPalClient ( final Collection < BaseClient > properties ) { val paypal = pac4jProperties . getPaypal ( ) ; if ( StringUtils . isNotBlank ( paypal . getId ( ) ) && StringUtils . isNotBlank ( paypal . getSecret ( ) ) ) { val client = new PayPalClient ( paypal . getId ( ) , paypal . getSecret ( ) ) ; configureClient ( client , paypal ) ; LOGGER . debug ( "Created client [{}] with identifier [{}]" , client . getName ( ) , client . getKey ( ) ) ; properties . add ( client ) ; } }
Configure paypal client .
17,617
protected void configureClient ( final BaseClient client , final Pac4jBaseClientProperties props ) { val cname = props . getClientName ( ) ; if ( StringUtils . isNotBlank ( cname ) ) { client . setName ( cname ) ; } else { val className = client . getClass ( ) . getSimpleName ( ) ; val genName = className . concat ( RandomStringUtils . randomNumeric ( 2 ) ) ; client . setName ( genName ) ; LOGGER . warn ( "Client name for [{}] is set to a generated value of [{}]. " + "Consider defining an explicit name for the delegated provider" , className , genName ) ; } val customProperties = client . getCustomProperties ( ) ; customProperties . put ( ClientCustomPropertyConstants . CLIENT_CUSTOM_PROPERTY_AUTO_REDIRECT , props . isAutoRedirect ( ) ) ; if ( StringUtils . isNotBlank ( props . getPrincipalAttributeId ( ) ) ) { customProperties . put ( ClientCustomPropertyConstants . CLIENT_CUSTOM_PROPERTY_PRINCIPAL_ATTRIBUTE_ID , props . getPrincipalAttributeId ( ) ) ; } }
Sets client name .
17,618
protected void configureCasClient ( final Collection < BaseClient > properties ) { val index = new AtomicInteger ( ) ; pac4jProperties . getCas ( ) . stream ( ) . filter ( cas -> StringUtils . isNotBlank ( cas . getLoginUrl ( ) ) ) . forEach ( cas -> { val cfg = new CasConfiguration ( cas . getLoginUrl ( ) , CasProtocol . valueOf ( cas . getProtocol ( ) ) ) ; cfg . setLogoutHandler ( casServerSpecificLogoutHandler ) ; val client = new CasClient ( cfg ) ; val count = index . intValue ( ) ; if ( StringUtils . isBlank ( cas . getClientName ( ) ) ) { client . setName ( client . getClass ( ) . getSimpleName ( ) + count ) ; } client . setCallbackUrlResolver ( new PathParameterCallbackUrlResolver ( ) ) ; configureClient ( client , cas ) ; index . incrementAndGet ( ) ; LOGGER . debug ( "Created client [{}]" , client ) ; properties . add ( client ) ; } ) ; }
Configure cas client .
17,619
protected void configureOAuth20Client ( final Collection < BaseClient > properties ) { val index = new AtomicInteger ( ) ; pac4jProperties . getOauth2 ( ) . stream ( ) . filter ( oauth -> StringUtils . isNotBlank ( oauth . getId ( ) ) && StringUtils . isNotBlank ( oauth . getSecret ( ) ) ) . forEach ( oauth -> { val client = new GenericOAuth20Client ( ) ; client . setKey ( oauth . getId ( ) ) ; client . setSecret ( oauth . getSecret ( ) ) ; client . setProfileAttrs ( oauth . getProfileAttrs ( ) ) ; client . setProfileNodePath ( oauth . getProfilePath ( ) ) ; client . setProfileUrl ( oauth . getProfileUrl ( ) ) ; client . setProfileVerb ( Verb . valueOf ( oauth . getProfileVerb ( ) . toUpperCase ( ) ) ) ; client . setTokenUrl ( oauth . getTokenUrl ( ) ) ; client . setAuthUrl ( oauth . getAuthUrl ( ) ) ; client . setCustomParams ( oauth . getCustomParams ( ) ) ; val count = index . intValue ( ) ; if ( StringUtils . isBlank ( oauth . getClientName ( ) ) ) { client . setName ( client . getClass ( ) . getSimpleName ( ) + count ) ; } client . setCallbackUrlResolver ( new PathParameterCallbackUrlResolver ( ) ) ; configureClient ( client , oauth ) ; index . incrementAndGet ( ) ; LOGGER . debug ( "Created client [{}]" , client ) ; properties . add ( client ) ; } ) ; }
Configure OAuth client .
17,620
protected void configureOidcClient ( final Collection < BaseClient > properties ) { pac4jProperties . getOidc ( ) . forEach ( oidc -> { val client = getOidcClientFrom ( oidc ) ; LOGGER . debug ( "Created client [{}]" , client ) ; properties . add ( client ) ; } ) ; }
Configure oidc client .
17,621
public Set < BaseClient > build ( ) { val clients = new LinkedHashSet < BaseClient > ( ) ; configureCasClient ( clients ) ; configureFacebookClient ( clients ) ; configureOidcClient ( clients ) ; configureOAuth20Client ( clients ) ; configureSamlClient ( clients ) ; configureTwitterClient ( clients ) ; configureDropBoxClient ( clients ) ; configureFoursquareClient ( clients ) ; configureGitHubClient ( clients ) ; configureGoogleClient ( clients ) ; configureWindowsLiveClient ( clients ) ; configureYahooClient ( clients ) ; configureLinkedInClient ( clients ) ; configurePayPalClient ( clients ) ; configureWordPressClient ( clients ) ; configureBitBucketClient ( clients ) ; configureOrcidClient ( clients ) ; configureHiOrgServerClient ( clients ) ; return clients ; }
Build set of clients configured .
17,622
protected RegisteredService getRegisteredServiceForConsent ( final RequestContext requestContext , final Service service ) { val serviceToUse = this . authenticationRequestServiceSelectionStrategies . resolveService ( service ) ; val registeredService = this . servicesManager . findServiceBy ( serviceToUse ) ; RegisteredServiceAccessStrategyUtils . ensureServiceAccessIsAllowed ( service , registeredService ) ; return registeredService ; }
Gets registered service for consent .
17,623
protected void prepareConsentForRequestContext ( final RequestContext requestContext ) { val consentProperties = casProperties . getConsent ( ) ; val originalService = WebUtils . getService ( requestContext ) ; val service = this . authenticationRequestServiceSelectionStrategies . resolveService ( originalService ) ; val registeredService = getRegisteredServiceForConsent ( requestContext , service ) ; val authentication = WebUtils . getAuthentication ( requestContext ) ; val attributes = consentEngine . resolveConsentableAttributesFrom ( authentication , service , registeredService ) ; val flowScope = requestContext . getFlowScope ( ) ; flowScope . put ( "attributes" , attributes ) ; WebUtils . putPrincipal ( requestContext , authentication . getPrincipal ( ) ) ; WebUtils . putServiceIntoFlashScope ( requestContext , service ) ; val decision = consentEngine . findConsentDecision ( service , registeredService , authentication ) ; flowScope . put ( "option" , decision == null ? ConsentReminderOptions . ATTRIBUTE_NAME . getValue ( ) : decision . getOptions ( ) . getValue ( ) ) ; val reminder = decision == null ? consentProperties . getReminder ( ) : decision . getReminder ( ) ; flowScope . put ( "reminder" , Long . valueOf ( reminder ) ) ; flowScope . put ( "reminderTimeUnit" , decision == null ? consentProperties . getReminderTimeUnit ( ) . name ( ) : decision . getReminderTimeUnit ( ) . name ( ) ) ; }
Prepare consent for request context . The original service is kept and the resolved service is added to the flash - scope only to ensure consent works for all other callback services that deal with different protocols .
17,624
@ View ( name = "by_type_and_local_date_time" , map = "function(doc) { emit([doc.type, doc.creationTime], doc) }" ) public List < CouchDbCasEvent > findByTypeSince ( final String type , final LocalDateTime localDateTime ) { val view = createQuery ( "by_type_and_local_date_time" ) . startKey ( ComplexKey . of ( type , localDateTime ) ) . endKey ( ComplexKey . of ( type , LocalDateTime . now ( ) ) ) ; return db . queryView ( view , CouchDbCasEvent . class ) ; }
Fund by type since a given date .
17,625
@ View ( name = "by_principal_id_since" , map = "function(doc) { emit([doc.principalId, doc.creationTime], doc) }" ) public Collection < CouchDbCasEvent > findByPrincipalSince ( final String principalId , final LocalDateTime creationTime ) { val view = createQuery ( "by_principal_id_since" ) . startKey ( ComplexKey . of ( principalId , creationTime ) ) . endKey ( ComplexKey . of ( principalId , LocalDateTime . now ( ) ) ) ; return db . queryView ( view , CouchDbCasEvent . class ) ; }
Find by principal .
17,626
protected ModelAndView generateResponseForDeviceToken ( final HttpServletRequest request , final HttpServletResponse response , final OAuth20AccessTokenResponseResult result ) { val model = getDeviceTokenResponseModel ( result ) ; return new ModelAndView ( new MappingJackson2JsonView ( MAPPER ) , model ) ; }
Generate response for device token model and view .
17,627
protected Map getDeviceTokenResponseModel ( final OAuth20AccessTokenResponseResult result ) { val model = new LinkedHashMap < String , Object > ( ) ; val uri = result . getCasProperties ( ) . getServer ( ) . getPrefix ( ) . concat ( OAuth20Constants . BASE_OAUTH20_URL ) . concat ( "/" ) . concat ( OAuth20Constants . DEVICE_AUTHZ_URL ) ; model . put ( OAuth20Constants . DEVICE_VERIFICATION_URI , uri ) ; model . put ( OAuth20Constants . EXPIRES_IN , result . getDeviceTokenTimeout ( ) ) ; val generatedToken = result . getGeneratedToken ( ) ; generatedToken . getUserCode ( ) . ifPresent ( c -> model . put ( OAuth20Constants . DEVICE_USER_CODE , c ) ) ; generatedToken . getDeviceCode ( ) . ifPresent ( c -> model . put ( OAuth20Constants . DEVICE_CODE , c ) ) ; model . put ( OAuth20Constants . DEVICE_INTERVAL , result . getDeviceRefreshInterval ( ) ) ; return model ; }
Gets device token response model .
17,628
protected ModelAndView generateResponseForAccessToken ( final HttpServletRequest request , final HttpServletResponse response , final OAuth20AccessTokenResponseResult result ) { val model = getAccessTokenResponseModel ( request , response , result ) ; return new ModelAndView ( new MappingJackson2JsonView ( MAPPER ) , model ) ; }
Generate response for access token model and view .
17,629
protected Map < String , Object > getAccessTokenResponseModel ( final HttpServletRequest request , final HttpServletResponse response , final OAuth20AccessTokenResponseResult result ) { val model = new LinkedHashMap < String , Object > ( ) ; val generatedToken = result . getGeneratedToken ( ) ; generatedToken . getAccessToken ( ) . ifPresent ( t -> { model . put ( OAuth20Constants . ACCESS_TOKEN , encodeAccessToken ( t , result ) ) ; model . put ( OAuth20Constants . SCOPE , t . getScopes ( ) . stream ( ) . collect ( joining ( " " ) ) ) ; } ) ; generatedToken . getRefreshToken ( ) . ifPresent ( t -> model . put ( OAuth20Constants . REFRESH_TOKEN , t . getId ( ) ) ) ; model . put ( OAuth20Constants . TOKEN_TYPE , OAuth20Constants . TOKEN_TYPE_BEARER ) ; model . put ( OAuth20Constants . EXPIRES_IN , result . getAccessTokenTimeout ( ) ) ; return model ; }
Generate internal .
17,630
protected boolean isRefreshTokenExpired ( final TicketState ticketState ) { if ( ticketState == null ) { return true ; } val expiringTime = ticketState . getCreationTime ( ) . plus ( this . timeToKillInSeconds , ChronoUnit . SECONDS ) ; return expiringTime . isBefore ( ZonedDateTime . now ( ZoneOffset . UTC ) ) ; }
Is refresh token expired ?
17,631
protected RegisteredService resolveRegisteredServiceInRequestContext ( final RequestContext requestContext ) { val resolvedService = resolveServiceFromAuthenticationRequest ( requestContext ) ; if ( resolvedService != null ) { val service = getWebflowEventResolutionConfigurationContext ( ) . getServicesManager ( ) . findServiceBy ( resolvedService ) ; RegisteredServiceAccessStrategyUtils . ensureServiceAccessIsAllowed ( resolvedService , service ) ; return service ; } LOGGER . debug ( "Authentication request is not accompanied by a service given none is specified" ) ; return null ; }
Resolve registered service in request context .
17,632
@ Scheduled ( initialDelayString = "${cas.authn.mfa.trusted.cleaner.schedule.startDelay:PT10S}" , fixedDelayString = "${cas.authn.mfa.trusted.cleaner.schedule.repeatInterval:PT60S}" ) public void clean ( ) { if ( ! trustedProperties . getCleaner ( ) . getSchedule ( ) . isEnabled ( ) ) { LOGGER . debug ( "[{}] is disabled. Expired trusted authentication records will not automatically be cleaned up by CAS" , getClass ( ) . getName ( ) ) ; return ; } try { LOGGER . debug ( "Proceeding to clean up expired trusted authentication records..." ) ; SpringBeanAutowiringSupport . processInjectionBasedOnCurrentContext ( this ) ; val validDate = LocalDateTime . now ( ) . minus ( trustedProperties . getExpiration ( ) , DateTimeUtils . toChronoUnit ( trustedProperties . getTimeUnit ( ) ) ) ; LOGGER . info ( "Expiring records that are on/before [{}]" , validDate ) ; this . storage . expire ( validDate ) ; } catch ( final Exception e ) { LOGGER . error ( e . getMessage ( ) , e ) ; } }
Clean up expired records .
17,633
private static boolean isGrantTypeSupported ( final String type , final OAuth20GrantTypes ... expectedTypes ) { LOGGER . debug ( "Grant type received: [{}]" , type ) ; for ( val expectedType : expectedTypes ) { if ( OAuth20Utils . isGrantType ( type , expectedType ) ) { return true ; } } LOGGER . error ( "Unsupported grant type: [{}]" , type ) ; return false ; }
Check the grant type against expected grant types .
17,634
protected boolean validateInternal ( final J2EContext context , final String grantType , final ProfileManager manager , final UserProfile userProfile ) { return false ; }
Validate internal .
17,635
protected Principal authenticateAndGetPrincipal ( final UsernamePasswordCredential credential ) throws GeneralSecurityException { val lc = getLoginContext ( credential ) ; try { lc . login ( ) ; val principals = lc . getSubject ( ) . getPrincipals ( ) ; LOGGER . debug ( "JAAS principals extracted from subject are [{}}" , principals ) ; if ( principals != null && ! principals . isEmpty ( ) ) { val secPrincipal = principals . iterator ( ) . next ( ) ; LOGGER . debug ( "JAAS principal detected from subject login context is [{}}" , secPrincipal . getName ( ) ) ; return this . principalFactory . createPrincipal ( secPrincipal . getName ( ) ) ; } } finally { if ( lc != null ) { lc . logout ( ) ; } } return null ; }
Authenticate and get principal principal .
17,636
protected LoginContext getLoginContext ( final UsernamePasswordCredential credential ) throws GeneralSecurityException { val callbackHandler = new UsernamePasswordCallbackHandler ( credential . getUsername ( ) , credential . getPassword ( ) ) ; if ( this . loginConfigurationFile != null && StringUtils . isNotBlank ( this . loginConfigType ) && this . loginConfigurationFile . exists ( ) && this . loginConfigurationFile . canRead ( ) ) { final Configuration . Parameters parameters = new URIParameter ( loginConfigurationFile . toURI ( ) ) ; val loginConfig = Configuration . getInstance ( this . loginConfigType , parameters ) ; return new LoginContext ( this . realm , null , callbackHandler , loginConfig ) ; } return new LoginContext ( this . realm , callbackHandler ) ; }
Gets login context .
17,637
private String buildMetadataGeneratorParameters ( final Pair < String , String > signing , final Pair < String , String > encryption ) { val template = samlIdPMetadataGeneratorConfigurationContext . getResourceLoader ( ) . getResource ( "classpath:/template-idp-metadata.xml" ) ; var signingCert = signing . getKey ( ) ; signingCert = StringUtils . remove ( signingCert , BEGIN_CERTIFICATE ) ; signingCert = StringUtils . remove ( signingCert , END_CERTIFICATE ) . trim ( ) ; var encryptionCert = encryption . getKey ( ) ; encryptionCert = StringUtils . remove ( encryptionCert , BEGIN_CERTIFICATE ) ; encryptionCert = StringUtils . remove ( encryptionCert , END_CERTIFICATE ) . trim ( ) ; try ( val writer = new StringWriter ( ) ) { IOUtils . copy ( template . getInputStream ( ) , writer , StandardCharsets . UTF_8 ) ; val metadata = writer . toString ( ) . replace ( "${entityId}" , samlIdPMetadataGeneratorConfigurationContext . getEntityId ( ) ) . replace ( "${scope}" , samlIdPMetadataGeneratorConfigurationContext . getScope ( ) ) . replace ( "${idpEndpointUrl}" , getIdPEndpointUrl ( ) ) . replace ( "${encryptionKey}" , encryptionCert ) . replace ( "${signingKey}" , signingCert ) ; writeMetadata ( metadata ) ; return metadata ; } }
Build metadata generator parameters by passing the encryption signing and back - channel certs to the parameter generator .
17,638
protected Pair < String , String > generateCertificateAndKey ( ) { try ( val certWriter = new StringWriter ( ) ; val keyWriter = new StringWriter ( ) ) { samlIdPMetadataGeneratorConfigurationContext . getSamlIdPCertificateAndKeyWriter ( ) . writeCertificateAndKey ( keyWriter , certWriter ) ; val encryptionKey = samlIdPMetadataGeneratorConfigurationContext . getMetadataCipherExecutor ( ) . encode ( keyWriter . toString ( ) ) ; return Pair . of ( certWriter . toString ( ) , encryptionKey ) ; } }
Generate certificate and key pair .
17,639
@ View ( name = "by_consent_decision" , map = "function(doc) {emit([doc.principal, doc.service], doc)}" ) public List < CouchDbConsentDecision > findConsentDecision ( final String principal , final String service ) { val view = createQuery ( "by_consent_decision" ) . key ( ComplexKey . of ( principal , service ) ) . includeDocs ( true ) ; return db . queryView ( view , CouchDbConsentDecision . class ) ; }
Find all consent decisions for a given principal service pair . Should only be one .
17,640
public CouchDbConsentDecision findFirstConsentDecision ( final String principal , final String service ) { val view = createQuery ( "by_consent_decision" ) . key ( ComplexKey . of ( principal , service ) ) . limit ( 1 ) . includeDocs ( true ) ; return db . queryView ( view , CouchDbConsentDecision . class ) . stream ( ) . findFirst ( ) . orElse ( null ) ; }
Find the first consent decision for a given principal service pair . Should only be one of them anyway .
17,641
@ View ( name = "by_principal_and_id" , map = "function(doc) {emit([doc.principal, doc.id], doc)}" ) public CouchDbConsentDecision findByPrincipalAndId ( final String principal , final long id ) { val view = createQuery ( "by_principal_and_id" ) . key ( ComplexKey . of ( principal , id ) ) . limit ( 1 ) . includeDocs ( true ) ; return db . queryView ( view , CouchDbConsentDecision . class ) . stream ( ) . findFirst ( ) . orElse ( null ) ; }
Find a consent decision by + long + ID and principal name . For CouchDb this ID is randomly generated and the pair should be unique with a very high probability but is not guaranteed . This method is mostly only used by tests .
17,642
public static IPAddressIntelligenceResponse allowed ( ) { return builder ( ) . status ( IPAddressIntelligenceStatus . ALLOWED ) . score ( IPAddressIntelligenceStatus . ALLOWED . getScore ( ) ) . build ( ) ; }
Allowed ip address intelligence response .
17,643
public static IPAddressIntelligenceResponse banned ( ) { return builder ( ) . status ( IPAddressIntelligenceStatus . BANNED ) . score ( IPAddressIntelligenceStatus . BANNED . getScore ( ) ) . build ( ) ; }
Banned ip address intelligence response .
17,644
public AcceptableUsagePolicyStatus setProperty ( final String name , final Object value ) { this . properties . remove ( name ) ; addProperty ( name , value ) ; return this ; }
Sets property .
17,645
public AcceptableUsagePolicyStatus addProperty ( final String name , final Object value ) { this . properties . put ( name , value ) ; return this ; }
Add property .
17,646
public void shutdown ( ) { try { LOGGER . info ( "Shutting down Hazelcast instance [{}]" , this . hazelcastInstance . getConfig ( ) . getInstanceName ( ) ) ; this . hazelcastInstance . shutdown ( ) ; } catch ( final Exception e ) { LOGGER . debug ( e . getMessage ( ) ) ; } }
Make sure we shutdown HazelCast when the context is destroyed .
17,647
private static Collection < MessageDescriptor > calculateAuthenticationWarningMessages ( final TicketGrantingTicket tgtId , final MessageContext messageContext ) { val entries = tgtId . getAuthentication ( ) . getSuccesses ( ) . entrySet ( ) ; val messages = entries . stream ( ) . map ( entry -> entry . getValue ( ) . getWarnings ( ) ) . filter ( entry -> ! entry . isEmpty ( ) ) . collect ( Collectors . toList ( ) ) ; messages . add ( tgtId . getAuthentication ( ) . getWarnings ( ) ) ; return messages . stream ( ) . flatMap ( Collection :: stream ) . peek ( message -> addMessageDescriptorToMessageContext ( messageContext , message ) ) . collect ( Collectors . toSet ( ) ) ; }
Add warning messages to message context if needed .
17,648
protected static void addMessageDescriptorToMessageContext ( final MessageContext context , final MessageDescriptor warning ) { val builder = new MessageBuilder ( ) . warning ( ) . code ( warning . getCode ( ) ) . defaultText ( warning . getDefaultMessage ( ) ) . args ( ( Object [ ] ) warning . getParams ( ) ) ; context . addMessage ( builder . build ( ) ) ; }
Adds a warning message to the message context .
17,649
protected TicketGrantingTicket createOrUpdateTicketGrantingTicket ( final AuthenticationResult authenticationResult , final Authentication authentication , final String ticketGrantingTicket ) { try { if ( shouldIssueTicketGrantingTicket ( authentication , ticketGrantingTicket ) ) { LOGGER . debug ( "Attempting to issue a new ticket-granting ticket..." ) ; return this . centralAuthenticationService . createTicketGrantingTicket ( authenticationResult ) ; } LOGGER . debug ( "Updating the existing ticket-granting ticket [{}]..." , ticketGrantingTicket ) ; val tgt = this . centralAuthenticationService . getTicket ( ticketGrantingTicket , TicketGrantingTicket . class ) ; tgt . getAuthentication ( ) . update ( authentication ) ; this . centralAuthenticationService . updateTicket ( tgt ) ; return tgt ; } catch ( final PrincipalException e ) { LOGGER . error ( e . getMessage ( ) , e ) ; throw e ; } catch ( final Exception e ) { LOGGER . error ( e . getMessage ( ) , e ) ; throw new InvalidTicketException ( ticketGrantingTicket ) ; } }
Create or update ticket granting ticket ticket granting ticket .
17,650
public static String signSamlResponse ( final String samlResponse , final PrivateKey privateKey , final PublicKey publicKey ) { val doc = constructDocumentFromXml ( samlResponse ) ; if ( doc != null ) { val signedElement = signSamlElement ( doc . getRootElement ( ) , privateKey , publicKey ) ; doc . setRootElement ( ( org . jdom . Element ) signedElement . detach ( ) ) ; return new XMLOutputter ( ) . outputString ( doc ) ; } throw new IllegalArgumentException ( "Error signing SAML Response: Null document" ) ; }
Sign SAML response .
17,651
public static Document constructDocumentFromXml ( final String xmlString ) { try { val builder = new SAXBuilder ( ) ; builder . setFeature ( "http://xml.org/sax/features/external-general-entities" , false ) ; builder . setFeature ( "http://apache.org/xml/features/disallow-doctype-decl" , true ) ; return builder . build ( new ByteArrayInputStream ( xmlString . getBytes ( Charset . defaultCharset ( ) ) ) ) ; } catch ( final Exception e ) { LOGGER . error ( e . getMessage ( ) , e ) ; return null ; } }
Construct document from xml string .
17,652
private static org . jdom . Element signSamlElement ( final org . jdom . Element element , final PrivateKey privKey , final PublicKey pubKey ) { try { val providerName = System . getProperty ( "jsr105Provider" , SIGNATURE_FACTORY_PROVIDER_CLASS ) ; val clazz = Class . forName ( providerName ) ; val sigFactory = XMLSignatureFactory . getInstance ( "DOM" , ( Provider ) clazz . getDeclaredConstructor ( ) . newInstance ( ) ) ; val envelopedTransform = CollectionUtils . wrap ( sigFactory . newTransform ( Transform . ENVELOPED , ( TransformParameterSpec ) null ) ) ; val ref = sigFactory . newReference ( StringUtils . EMPTY , sigFactory . newDigestMethod ( DigestMethod . SHA1 , null ) , envelopedTransform , null , null ) ; val signatureMethod = getSignatureMethodFromPublicKey ( pubKey , sigFactory ) ; val canonicalizationMethod = sigFactory . newCanonicalizationMethod ( CanonicalizationMethod . INCLUSIVE_WITH_COMMENTS , ( C14NMethodParameterSpec ) null ) ; val signedInfo = sigFactory . newSignedInfo ( canonicalizationMethod , signatureMethod , CollectionUtils . wrap ( ref ) ) ; val keyInfoFactory = sigFactory . getKeyInfoFactory ( ) ; val keyValuePair = keyInfoFactory . newKeyValue ( pubKey ) ; val keyInfo = keyInfoFactory . newKeyInfo ( CollectionUtils . wrap ( keyValuePair ) ) ; val w3cElement = toDom ( element ) ; val dsc = new DOMSignContext ( privKey , w3cElement ) ; val xmlSigInsertionPoint = getXmlSignatureInsertLocation ( w3cElement ) ; dsc . setNextSibling ( xmlSigInsertionPoint ) ; val signature = sigFactory . newXMLSignature ( signedInfo , keyInfo ) ; signature . sign ( dsc ) ; return toJdom ( w3cElement ) ; } catch ( final Exception e ) { throw new IllegalArgumentException ( "Error signing SAML element: " + e . getMessage ( ) , e ) ; } }
Sign SAML element .
17,653
private static Node getXmlSignatureInsertLocation ( final Element elem ) { val nodeListExtensions = elem . getElementsByTagNameNS ( SAMLConstants . SAML20P_NS , "Extensions" ) ; if ( nodeListExtensions . getLength ( ) != 0 ) { return nodeListExtensions . item ( nodeListExtensions . getLength ( ) - 1 ) ; } val nodeListStatus = elem . getElementsByTagNameNS ( SAMLConstants . SAML20P_NS , "Status" ) ; return nodeListStatus . item ( nodeListStatus . getLength ( ) - 1 ) ; }
Gets the xml signature insert location .
17,654
private static Element toDom ( final org . jdom . Element element ) { return toDom ( element . getDocument ( ) ) . getDocumentElement ( ) ; }
Convert the received jdom element to an Element .
17,655
private static org . w3c . dom . Document toDom ( final Document doc ) { try { val xmlOutputter = new XMLOutputter ( ) ; val elemStrWriter = new StringWriter ( ) ; xmlOutputter . output ( doc , elemStrWriter ) ; val xmlBytes = elemStrWriter . toString ( ) . getBytes ( Charset . defaultCharset ( ) ) ; val dbf = DocumentBuilderFactory . newInstance ( ) ; dbf . setNamespaceAware ( true ) ; dbf . setFeature ( XMLConstants . FEATURE_SECURE_PROCESSING , true ) ; dbf . setFeature ( "http://apache.org/xml/features/disallow-doctype-decl" , true ) ; dbf . setFeature ( "http://apache.org/xml/features/validation/schema/normalized-value" , false ) ; dbf . setFeature ( "http://javax.xml.XMLConstants/feature/secure-processing" , true ) ; dbf . setFeature ( "http://xml.org/sax/features/external-general-entities" , false ) ; dbf . setFeature ( "http://xml.org/sax/features/external-parameter-entities" , false ) ; return dbf . newDocumentBuilder ( ) . parse ( new ByteArrayInputStream ( xmlBytes ) ) ; } catch ( final Exception e ) { LOGGER . trace ( e . getMessage ( ) , e ) ; return null ; } }
Convert the received jdom doc to a Document element .
17,656
public < T extends SAMLObject > T newSamlObject ( final Class < T > objectType ) { val qName = getSamlObjectQName ( objectType ) ; val builder = ( SAMLObjectBuilder < T > ) XMLObjectProviderRegistrySupport . getBuilderFactory ( ) . getBuilder ( qName ) ; if ( builder == null ) { throw new IllegalStateException ( "No SAML object builder is registered for class " + objectType . getName ( ) ) ; } return objectType . cast ( builder . buildObject ( qName ) ) ; }
Create a new SAML object .
17,657
public < T extends SOAPObject > T newSoapObject ( final Class < T > objectType ) { val qName = getSamlObjectQName ( objectType ) ; val builder = ( SOAPObjectBuilder < T > ) XMLObjectProviderRegistrySupport . getBuilderFactory ( ) . getBuilder ( qName ) ; if ( builder == null ) { throw new IllegalStateException ( "No SAML object builder is registered for class " + objectType . getName ( ) ) ; } return objectType . cast ( builder . buildObject ( qName ) ) ; }
New soap object t .
17,658
public QName getSamlObjectQName ( final Class objectType ) { try { val f = objectType . getField ( DEFAULT_ELEMENT_NAME_FIELD ) ; return ( QName ) f . get ( null ) ; } catch ( final NoSuchFieldException e ) { throw new IllegalStateException ( "Cannot find field " + objectType . getName ( ) + '.' + DEFAULT_ELEMENT_NAME_FIELD , e ) ; } catch ( final IllegalAccessException e ) { throw new IllegalStateException ( "Cannot access field " + objectType . getName ( ) + '.' + DEFAULT_ELEMENT_NAME_FIELD , e ) ; } }
Gets saml object QName .
17,659
protected XMLObject newAttributeValue ( final Object value , final String valueType , final QName elementName ) { if ( XSString . class . getSimpleName ( ) . equalsIgnoreCase ( valueType ) ) { val builder = new XSStringBuilder ( ) ; val attrValueObj = builder . buildObject ( elementName , XSString . TYPE_NAME ) ; attrValueObj . setValue ( value . toString ( ) ) ; return attrValueObj ; } if ( XSURI . class . getSimpleName ( ) . equalsIgnoreCase ( valueType ) ) { val builder = new XSURIBuilder ( ) ; val attrValueObj = builder . buildObject ( elementName , XSURI . TYPE_NAME ) ; attrValueObj . setValue ( value . toString ( ) ) ; return attrValueObj ; } if ( XSBoolean . class . getSimpleName ( ) . equalsIgnoreCase ( valueType ) ) { val builder = new XSBooleanBuilder ( ) ; val attrValueObj = builder . buildObject ( elementName , XSBoolean . TYPE_NAME ) ; attrValueObj . setValue ( XSBooleanValue . valueOf ( value . toString ( ) . toLowerCase ( ) ) ) ; return attrValueObj ; } if ( XSInteger . class . getSimpleName ( ) . equalsIgnoreCase ( valueType ) ) { val builder = new XSIntegerBuilder ( ) ; val attrValueObj = builder . buildObject ( elementName , XSInteger . TYPE_NAME ) ; attrValueObj . setValue ( Integer . valueOf ( value . toString ( ) ) ) ; return attrValueObj ; } if ( XSDateTime . class . getSimpleName ( ) . equalsIgnoreCase ( valueType ) ) { val builder = new XSDateTimeBuilder ( ) ; val attrValueObj = builder . buildObject ( elementName , XSDateTime . TYPE_NAME ) ; attrValueObj . setValue ( DateTime . parse ( value . toString ( ) ) ) ; return attrValueObj ; } if ( XSBase64Binary . class . getSimpleName ( ) . equalsIgnoreCase ( valueType ) ) { val builder = new XSBase64BinaryBuilder ( ) ; val attrValueObj = builder . buildObject ( elementName , XSBase64Binary . TYPE_NAME ) ; attrValueObj . setValue ( value . toString ( ) ) ; return attrValueObj ; } if ( XSObject . class . getSimpleName ( ) . equalsIgnoreCase ( valueType ) ) { val mapper = new JacksonXmlSerializer ( ) ; val builder = new XSAnyBuilder ( ) ; val attrValueObj = builder . buildObject ( elementName ) ; attrValueObj . setTextContent ( mapper . writeValueAsString ( value ) ) ; return attrValueObj ; } val builder = new XSAnyBuilder ( ) ; val attrValueObj = builder . buildObject ( elementName ) ; attrValueObj . setTextContent ( value . toString ( ) ) ; return attrValueObj ; }
New attribute value .
17,660
public String generateSecureRandomId ( ) { try { val random = new HexRandomStringGenerator ( RANDOM_ID_SIZE ) ; val hex = random . getNewString ( ) ; if ( StringUtils . isBlank ( hex ) ) { throw new IllegalArgumentException ( "Could not generate a secure random id based on " + random . getAlgorithm ( ) ) ; } return '_' + hex ; } catch ( final Exception e ) { throw new IllegalStateException ( "Cannot create secure random ID generator for SAML message IDs." , e ) ; } }
Generate a secure random id .
17,661
protected void addAttributeValuesToSamlAttribute ( final String attributeName , final Object attributeValue , final String valueType , final List < XMLObject > attributeList , final QName defaultElementName ) { if ( attributeValue == null ) { LOGGER . debug ( "Skipping over SAML attribute [{}] since it has no value" , attributeName ) ; return ; } LOGGER . trace ( "Attempting to generate SAML attribute [{}] with value(s) [{}]" , attributeName , attributeValue ) ; if ( attributeValue instanceof Collection < ? > ) { val c = ( Collection < ? > ) attributeValue ; LOGGER . debug ( "Generating multi-valued SAML attribute [{}] with values [{}]" , attributeName , c ) ; c . stream ( ) . map ( value -> newAttributeValue ( value , valueType , defaultElementName ) ) . forEach ( attributeList :: add ) ; } else { LOGGER . debug ( "Generating SAML attribute [{}] with value [{}]" , attributeName , attributeValue ) ; attributeList . add ( newAttributeValue ( attributeValue , valueType , defaultElementName ) ) ; } }
Add attribute values to saml attribute .
17,662
public String getPrincipalAttributeValue ( final Principal p , final String attributeName ) { val attributes = p . getAttributes ( ) ; if ( attributes . containsKey ( attributeName ) ) { return CollectionUtils . toCollection ( attributes . get ( attributeName ) ) . iterator ( ) . next ( ) . toString ( ) ; } return null ; }
Gets principal attribute value .
17,663
public static SplunkAppender build ( @ PluginAttribute ( "name" ) final String name , @ PluginElement ( "AppenderRef" ) final AppenderRef appenderRef , final Configuration config ) { return new SplunkAppender ( name , config , appenderRef ) ; }
Create appender .
17,664
public Principal buildSurrogatePrincipal ( final String surrogate , final Principal primaryPrincipal , final Credential credentials , final RegisteredService registeredService ) { val repositories = new HashSet < String > ( 0 ) ; if ( registeredService != null ) { repositories . addAll ( registeredService . getAttributeReleasePolicy ( ) . getPrincipalAttributesRepository ( ) . getAttributeRepositoryIds ( ) ) ; } val attributes = ( Map ) CoreAuthenticationUtils . retrieveAttributesFromAttributeRepository ( attributeRepository , surrogate , repositories ) ; val principal = principalFactory . createPrincipal ( surrogate , attributes ) ; return new SurrogatePrincipal ( primaryPrincipal , principal ) ; }
Build principal .
17,665
public Optional < AuthenticationResultBuilder > buildSurrogateAuthenticationResult ( final AuthenticationResultBuilder authenticationResultBuilder , final Credential credential , final String surrogateTargetId , final RegisteredService registeredService ) { val currentAuthn = authenticationResultBuilder . getInitialAuthentication ( ) ; if ( currentAuthn . isPresent ( ) ) { val authentication = currentAuthn . get ( ) ; val surrogatePrincipal = buildSurrogatePrincipal ( surrogateTargetId , authentication . getPrincipal ( ) , credential , registeredService ) ; val auth = DefaultAuthenticationBuilder . newInstance ( authentication ) . setPrincipal ( surrogatePrincipal ) . build ( ) ; return Optional . of ( authenticationResultBuilder . collect ( auth ) ) ; } return Optional . empty ( ) ; }
Build surrogate authentication result optional .
17,666
public String getDecodedValue ( ) { if ( EncodingUtils . isBase64 ( value ) ) { return EncodingUtils . decodeBase64ToString ( value ) ; } return value ; }
Gets base - 64 decoded value if needed or the value itself .
17,667
protected boolean doRequiredAttributesAllowPrincipalAccess ( final Map < String , Object > principalAttributes , final Map < String , Set < String > > requiredAttributes ) { LOGGER . debug ( "These required attributes [{}] are examined against [{}] before service can proceed." , requiredAttributes , principalAttributes ) ; if ( requiredAttributes . isEmpty ( ) ) { return true ; } return requiredAttributesFoundInMap ( principalAttributes , requiredAttributes ) ; }
Do required attributes allow principal access boolean .
17,668
protected boolean doRejectedAttributesRefusePrincipalAccess ( final Map < String , Object > principalAttributes ) { LOGGER . debug ( "These rejected attributes [{}] are examined against [{}] before service can proceed." , rejectedAttributes , principalAttributes ) ; if ( rejectedAttributes . isEmpty ( ) ) { return false ; } return requiredAttributesFoundInMap ( principalAttributes , rejectedAttributes ) ; }
Do rejected attributes refuse principal access boolean .
17,669
protected boolean enoughAttributesAvailableToProcess ( final String principal , final Map < String , Object > principalAttributes ) { if ( ! enoughRequiredAttributesAvailableToProcess ( principalAttributes , this . requiredAttributes ) ) { return false ; } if ( principalAttributes . size ( ) < this . rejectedAttributes . size ( ) ) { LOGGER . debug ( "The size of the principal attributes that are [{}] does not match defined rejected attributes, " + "which means the principal is not carrying enough data to grant authorization" , principalAttributes ) ; return false ; } return true ; }
Enough attributes available to process? Check collection sizes and determine if we have enough data to move on .
17,670
protected boolean enoughRequiredAttributesAvailableToProcess ( final Map < String , Object > principalAttributes , final Map < String , Set < String > > requiredAttributes ) { if ( principalAttributes . isEmpty ( ) && ! requiredAttributes . isEmpty ( ) ) { LOGGER . debug ( "No principal attributes are found to satisfy defined attribute requirements" ) ; return false ; } if ( principalAttributes . size ( ) < requiredAttributes . size ( ) ) { LOGGER . debug ( "The size of the principal attributes that are [{}] does not match defined required attributes, " + "which indicates the principal is not carrying enough data to grant authorization" , principalAttributes ) ; return false ; } return true ; }
Enough required attributes available to process? Check collection sizes and determine if we have enough data to move on .
17,671
protected boolean requiredAttributesFoundInMap ( final Map < String , Object > principalAttributes , final Map < String , Set < String > > requiredAttributes ) { val difference = requiredAttributes . keySet ( ) . stream ( ) . filter ( a -> principalAttributes . keySet ( ) . contains ( a ) ) . collect ( Collectors . toSet ( ) ) ; LOGGER . debug ( "Difference of checking required attributes: [{}]" , difference ) ; if ( this . requireAllAttributes && difference . size ( ) < requiredAttributes . size ( ) ) { return false ; } if ( this . requireAllAttributes ) { return difference . stream ( ) . allMatch ( key -> requiredAttributeFound ( key , principalAttributes , requiredAttributes ) ) ; } return difference . stream ( ) . anyMatch ( key -> requiredAttributeFound ( key , principalAttributes , requiredAttributes ) ) ; }
Check whether required attributes are found in the given map .
17,672
private static Collection < String > getStringValues ( final List < ? > items ) { val list = new ArrayList < String > ( ) ; items . forEach ( d -> { if ( d instanceof XSURI ) { list . add ( ( ( XSURI ) d ) . getValue ( ) ) ; } else if ( d instanceof XSString ) { list . add ( ( ( XSString ) d ) . getValue ( ) ) ; } } ) ; return list ; }
Gets string values from the list of mdui objects .
17,673
public Collection < Logo > getLogoUrls ( ) { val list = new ArrayList < Logo > ( ) ; if ( this . uiInfo != null ) { list . addAll ( this . uiInfo . getLogos ( ) . stream ( ) . map ( l -> new Logo ( l . getURL ( ) , l . getHeight ( ) , l . getWidth ( ) ) ) . collect ( Collectors . toList ( ) ) ) ; } return list ; }
Gets logo urls .
17,674
public String getDescription ( final String locale ) { if ( this . uiInfo != null ) { val description = getLocalizedValues ( locale , this . uiInfo . getDescriptions ( ) ) ; return description != null ? description : super . getDescription ( ) ; } return super . getDescription ( ) ; }
Gets localized description .
17,675
public String getDisplayName ( final String locale ) { if ( this . uiInfo != null ) { val displayName = getLocalizedValues ( locale , this . uiInfo . getDisplayNames ( ) ) ; return displayName != null ? displayName : super . getDisplayName ( ) ; } return super . getDisplayName ( ) ; }
Gets localized displayName .
17,676
public String getInformationURL ( final String locale ) { if ( this . uiInfo != null ) { val informationUrl = getLocalizedValues ( locale , this . uiInfo . getInformationURLs ( ) ) ; return informationUrl != null ? informationUrl : super . getInformationURL ( ) ; } return super . getInformationURL ( ) ; }
Gets localized informationURL .
17,677
public String getPrivacyStatementURL ( final String locale ) { if ( this . uiInfo != null ) { val privacyStatementURL = getLocalizedValues ( locale , this . uiInfo . getPrivacyStatementURLs ( ) ) ; return privacyStatementURL != null ? privacyStatementURL : super . getPrivacyStatementURL ( ) ; } return super . getPrivacyStatementURL ( ) ; }
Gets localized privacyStatementURL .
17,678
private static String getLocalizedValues ( final String locale , final List < ? > items ) { val foundLocale = findLocale ( StringUtils . defaultString ( locale , "en" ) , items ) ; if ( foundLocale . isPresent ( ) ) { return foundLocale . get ( ) ; } if ( ! items . isEmpty ( ) ) { val item = items . get ( 0 ) ; var value = StringUtils . EMPTY ; if ( item instanceof LocalizedName ) { value = ( ( LocalizedName ) item ) . getValue ( ) ; } if ( item instanceof LocalizedURI ) { value = ( ( LocalizedURI ) item ) . getValue ( ) ; } if ( item instanceof XSString ) { value = ( ( XSString ) item ) . getValue ( ) ; } LOGGER . trace ( "Loading first available locale [{}]" , value ) ; return value ; } return null ; }
Gets localized values .
17,679
public List < String > getSupportedNameIdFormats ( ) { val nameIdFormats = new ArrayList < String > ( ) ; val children = this . ssoDescriptor . getOrderedChildren ( ) ; if ( children != null ) { nameIdFormats . addAll ( children . stream ( ) . filter ( NameIDFormat . class :: isInstance ) . map ( child -> ( ( NameIDFormat ) child ) . getFormat ( ) ) . collect ( Collectors . toList ( ) ) ) ; } return nameIdFormats ; }
Gets supported name formats .
17,680
public SingleLogoutService getSingleLogoutService ( final String binding ) { return getSingleLogoutServices ( ) . stream ( ) . filter ( acs -> acs . getBinding ( ) . equalsIgnoreCase ( binding ) ) . findFirst ( ) . orElse ( null ) ; }
Gets single logout service for the requested binding .
17,681
public AssertionConsumerService getAssertionConsumerService ( final String binding ) { return getAssertionConsumerServices ( ) . stream ( ) . filter ( acs -> acs . getBinding ( ) . equalsIgnoreCase ( binding ) ) . findFirst ( ) . orElse ( null ) ; }
Gets assertion consumer service .
17,682
protected Set < Event > resolveCandidateAuthenticationEvents ( final RequestContext context , final Service service , final RegisteredService registeredService ) { val byEventId = Comparator . comparing ( Event :: getId ) ; val supplier = ( Supplier < TreeSet < Event > > ) ( ) -> new TreeSet < > ( byEventId ) ; return this . orderedResolvers . stream ( ) . map ( resolver -> { LOGGER . debug ( "Resolving candidate authentication event for service [{}] using [{}]" , service , resolver . getName ( ) ) ; return resolver . resolveSingle ( context ) ; } ) . filter ( Objects :: nonNull ) . collect ( Collectors . toCollection ( supplier ) ) ; }
Resolve candidate authentication events set .
17,683
public static HttpServletRequest getHttpServletRequestFromExternalWebflowContext ( final RequestContext context ) { Assert . isInstanceOf ( ServletExternalContext . class , context . getExternalContext ( ) , "Cannot obtain HttpServletRequest from event of type: " + context . getExternalContext ( ) . getClass ( ) . getName ( ) ) ; return ( HttpServletRequest ) context . getExternalContext ( ) . getNativeRequest ( ) ; }
Gets the http servlet request from the context .
17,684
public static HttpServletRequest getHttpServletRequestFromExternalWebflowContext ( ) { val servletExternalContext = ( ServletExternalContext ) ExternalContextHolder . getExternalContext ( ) ; if ( servletExternalContext != null ) { return ( HttpServletRequest ) servletExternalContext . getNativeRequest ( ) ; } return null ; }
Gets the http servlet request from the current servlet context .
17,685
public static HttpServletResponse getHttpServletResponseFromExternalWebflowContext ( final RequestContext context ) { Assert . isInstanceOf ( ServletExternalContext . class , context . getExternalContext ( ) , "Cannot obtain HttpServletResponse from event of type: " + context . getExternalContext ( ) . getClass ( ) . getName ( ) ) ; return ( HttpServletResponse ) context . getExternalContext ( ) . getNativeResponse ( ) ; }
Gets the http servlet response from the context .
17,686
public static HttpServletResponse getHttpServletResponseFromExternalWebflowContext ( ) { val servletExternalContext = ( ServletExternalContext ) ExternalContextHolder . getExternalContext ( ) ; if ( servletExternalContext != null ) { return ( HttpServletResponse ) servletExternalContext . getNativeResponse ( ) ; } return null ; }
Gets the http servlet response from the current servlet context .
17,687
public static WebApplicationService getService ( final List < ArgumentExtractor > argumentExtractors , final RequestContext context ) { val request = WebUtils . getHttpServletRequestFromExternalWebflowContext ( context ) ; return HttpRequestUtils . getService ( argumentExtractors , request ) ; }
Gets the service .
17,688
public static WebApplicationService getService ( final RequestContext context ) { return context != null ? ( WebApplicationService ) context . getFlowScope ( ) . get ( PARAMETER_SERVICE ) : null ; }
Gets the service from the flow scope .
17,689
public static RegisteredService getRegisteredService ( final RequestContext context ) { return context != null ? ( RegisteredService ) context . getFlowScope ( ) . get ( PARAMETER_REGISTERED_SERVICE ) : null ; }
Gets the registered service from the flow scope .
17,690
public static String getTicketGrantingTicketId ( final RequestContext context ) { val tgtFromRequest = getTicketGrantingTicketIdFrom ( context . getRequestScope ( ) ) ; val tgtFromFlow = getTicketGrantingTicketIdFrom ( context . getFlowScope ( ) ) ; return tgtFromRequest != null ? tgtFromRequest : tgtFromFlow ; }
Gets the ticket granting ticket id from the request and flow scopes .
17,691
public static void putServiceTicketInRequestScope ( final RequestContext context , final ServiceTicket ticketValue ) { context . getRequestScope ( ) . put ( PARAMETER_SERVICE_TICKET_ID , ticketValue . getId ( ) ) ; }
Put service ticket in request scope .
17,692
public static void putUnauthorizedRedirectUrlIntoFlowScope ( final RequestContext context , final URI url ) { context . getFlowScope ( ) . put ( PARAMETER_UNAUTHORIZED_REDIRECT_URL , url ) ; }
Adds the unauthorized redirect url to the flow scope .
17,693
public static void putLogoutRequests ( final RequestContext context , final List < SingleLogoutRequest > requests ) { context . getFlowScope ( ) . put ( PARAMETER_LOGOUT_REQUESTS , requests ) ; }
Put logout requests into flow scope .
17,694
public static List < SingleLogoutRequest > getLogoutRequests ( final RequestContext context ) { return ( List < SingleLogoutRequest > ) context . getFlowScope ( ) . get ( PARAMETER_LOGOUT_REQUESTS ) ; }
Gets the logout requests from flow scope .
17,695
public static void putServiceIntoFlowScope ( final RequestContext context , final Service service ) { context . getFlowScope ( ) . put ( PARAMETER_SERVICE , service ) ; }
Put service into flowscope .
17,696
public static void putServiceIntoFlashScope ( final RequestContext context , final Service service ) { context . getFlashScope ( ) . put ( PARAMETER_SERVICE , service ) ; }
Put service into flashscope .
17,697
public static boolean getWarningCookie ( final RequestContext context ) { val val = ObjectUtils . defaultIfNull ( context . getFlowScope ( ) . get ( "warnCookieValue" ) , Boolean . FALSE . toString ( ) ) . toString ( ) ; return Boolean . parseBoolean ( val ) ; }
Gets warning cookie .
17,698
public static void putRegisteredService ( final RequestContext context , final RegisteredService registeredService ) { context . getFlowScope ( ) . put ( PARAMETER_REGISTERED_SERVICE , registeredService ) ; }
Put registered service into flowscope .
17,699
public static < T extends Credential > T getCredential ( final RequestContext context , final Class < T > clazz ) { val credential = getCredential ( context ) ; if ( credential == null ) { return null ; } if ( ! clazz . isAssignableFrom ( credential . getClass ( ) ) ) { throw new ClassCastException ( "credential [" + credential . getId ( ) + " is of type " + credential . getClass ( ) + " when we were expecting " + clazz ) ; } return ( T ) credential ; }
Gets credential .