idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
18,300 | public static String createNonce ( ) { val fmtDate = ZonedDateTime . now ( ZoneOffset . UTC ) . toString ( ) ; val rand = RandomUtils . getNativeInstance ( ) ; val randomInt = rand . nextInt ( ) ; return DigestUtils . md5Hex ( fmtDate + randomInt ) ; } | Create nonce string . |
18,301 | public static String createOpaque ( final String domain , final String nonce ) { return DigestUtils . md5Hex ( domain + nonce ) ; } | Create opaque . |
18,302 | public static String createAuthenticateHeader ( final String realm , final String authMethod , final String nonce ) { val stringBuilder = new StringBuilder ( "Digest realm=\"" ) . append ( realm ) . append ( "\"," ) ; if ( StringUtils . isNotBlank ( authMethod ) ) { stringBuilder . append ( "qop=" ) . append ( authMethod ) . append ( ',' ) ; } return stringBuilder . append ( "nonce=\"" ) . append ( nonce ) . append ( "\",opaque=\"" ) . append ( createOpaque ( realm , nonce ) ) . append ( '"' ) . toString ( ) ; } | Create authenticate header containing the realm nonce opaque etc . |
18,303 | public WebEndpointResponse < Resource > exportServices ( ) throws Exception { val date = new SimpleDateFormat ( "yyyy-MM-dd-HH-mm" ) . format ( new Date ( ) ) ; val file = File . createTempFile ( "services-" + date , ".zip" ) ; Files . deleteIfExists ( file . toPath ( ) ) ; val env = new HashMap < String , Object > ( ) ; env . put ( "create" , "true" ) ; env . put ( "encoding" , StandardCharsets . UTF_8 . name ( ) ) ; try ( val zipfs = FileSystems . newFileSystem ( URI . create ( "jar:" + file . toURI ( ) . toString ( ) ) , env ) ) { val serializer = new RegisteredServiceJsonSerializer ( ) ; val services = this . servicesManager . load ( ) ; services . forEach ( Unchecked . consumer ( service -> { val fileName = String . format ( "%s-%s" , service . getName ( ) , service . getId ( ) ) ; val sourceFile = File . createTempFile ( fileName , ".json" ) ; serializer . to ( sourceFile , service ) ; if ( sourceFile . exists ( ) ) { val pathInZipfile = zipfs . getPath ( "/" . concat ( sourceFile . getName ( ) ) ) ; Files . copy ( sourceFile . toPath ( ) , pathInZipfile , StandardCopyOption . REPLACE_EXISTING ) ; } } ) ) ; } val resource = new TemporaryFileSystemResource ( file ) ; return new WebEndpointResponse ( resource ) ; } | Export services web endpoint response . |
18,304 | public Service buildService ( final OAuthRegisteredService registeredService , final J2EContext context , final boolean useServiceHeader ) { var id = StringUtils . EMPTY ; if ( useServiceHeader ) { id = OAuth20Utils . getServiceRequestHeaderIfAny ( context . getRequest ( ) ) ; LOGGER . debug ( "Located service based on request header is [{}]" , id ) ; } if ( StringUtils . isBlank ( id ) ) { id = registeredService . getClientId ( ) ; } return webApplicationServiceServiceFactory . createService ( id ) ; } | Build service . |
18,305 | public Authentication build ( final UserProfile profile , final OAuthRegisteredService registeredService , final J2EContext context , final Service service ) { val profileAttributes = CoreAuthenticationUtils . convertAttributeValuesToMultiValuedObjects ( profile . getAttributes ( ) ) ; val newPrincipal = this . principalFactory . createPrincipal ( profile . getId ( ) , profileAttributes ) ; LOGGER . debug ( "Created final principal [{}] after filtering attributes based on [{}]" , newPrincipal , registeredService ) ; val authenticator = profile . getClass ( ) . getCanonicalName ( ) ; val metadata = new BasicCredentialMetaData ( new BasicIdentifiableCredential ( profile . getId ( ) ) ) ; val handlerResult = new DefaultAuthenticationHandlerExecutionResult ( authenticator , metadata , newPrincipal , new ArrayList < > ( ) ) ; val scopes = CollectionUtils . toCollection ( context . getRequest ( ) . getParameterValues ( OAuth20Constants . SCOPE ) ) ; val state = StringUtils . defaultIfBlank ( context . getRequestParameter ( OAuth20Constants . STATE ) , StringUtils . EMPTY ) ; val nonce = StringUtils . defaultIfBlank ( context . getRequestParameter ( OAuth20Constants . NONCE ) , StringUtils . EMPTY ) ; LOGGER . debug ( "OAuth [{}] is [{}], and [{}] is [{}]" , OAuth20Constants . STATE , state , OAuth20Constants . NONCE , nonce ) ; return DefaultAuthenticationBuilder . newInstance ( ) . addAttribute ( "permissions" , new LinkedHashSet < > ( profile . getPermissions ( ) ) ) . addAttribute ( "roles" , new LinkedHashSet < > ( profile . getRoles ( ) ) ) . addAttribute ( "scopes" , scopes ) . addAttribute ( OAuth20Constants . STATE , state ) . addAttribute ( OAuth20Constants . NONCE , nonce ) . addAttribute ( OAuth20Constants . CLIENT_ID , registeredService . getClientId ( ) ) . addCredential ( metadata ) . setPrincipal ( newPrincipal ) . setAuthenticationDate ( ZonedDateTime . now ( ZoneOffset . UTC ) ) . addSuccess ( profile . getClass ( ) . getCanonicalName ( ) , handlerResult ) . build ( ) ; } | Create an authentication from a user profile . |
18,306 | protected void configureEndpointAccessToDenyUndefined ( final HttpSecurity http , final ExpressionUrlAuthorizationConfigurer < HttpSecurity > . ExpressionInterceptUrlRegistry requests ) { val endpoints = casProperties . getMonitor ( ) . getEndpoints ( ) . getEndpoint ( ) . keySet ( ) ; val endpointDefaults = casProperties . getMonitor ( ) . getEndpoints ( ) . getDefaultEndpointProperties ( ) ; pathMappedEndpoints . forEach ( endpoint -> { val rootPath = endpoint . getRootPath ( ) ; if ( endpoints . contains ( rootPath ) ) { LOGGER . trace ( "Endpoint security is defined for endpoint [{}]" , rootPath ) ; } else { val defaultAccessRules = endpointDefaults . getAccess ( ) ; LOGGER . trace ( "Endpoint security is NOT defined for endpoint [{}]. Using default security rules [{}]" , rootPath , endpointDefaults ) ; val endpointRequest = EndpointRequest . to ( rootPath ) . excludingLinks ( ) ; defaultAccessRules . forEach ( Unchecked . consumer ( access -> configureEndpointAccess ( http , requests , access , endpointDefaults , endpointRequest ) ) ) ; } } ) ; } | Configure endpoint access to deny undefined . |
18,307 | protected void configureJdbcAuthenticationProvider ( final AuthenticationManagerBuilder auth , final MonitorProperties . Endpoints . JdbcSecurity jdbc ) throws Exception { val cfg = auth . jdbcAuthentication ( ) ; cfg . usersByUsernameQuery ( jdbc . getQuery ( ) ) ; cfg . rolePrefix ( jdbc . getRolePrefix ( ) ) ; cfg . dataSource ( JpaBeans . newDataSource ( jdbc ) ) ; cfg . passwordEncoder ( PasswordEncoderUtils . newPasswordEncoder ( jdbc . getPasswordEncoder ( ) ) ) ; } | Configure jdbc authentication provider . |
18,308 | protected void configureLdapAuthenticationProvider ( final AuthenticationManagerBuilder auth , final MonitorProperties . Endpoints . LdapSecurity ldap ) { if ( isLdapAuthorizationActive ( ) ) { val p = new MonitorEndpointLdapAuthenticationProvider ( ldap , securityProperties ) ; auth . authenticationProvider ( p ) ; } else { LOGGER . trace ( "LDAP authorization is undefined, given no LDAP url, base-dn, search filter or role/group filter is configured" ) ; } } | Configure ldap authentication provider . |
18,309 | protected void configureJaasAuthenticationProvider ( final AuthenticationManagerBuilder auth , final MonitorProperties . Endpoints . JaasSecurity jaas ) throws Exception { val p = new JaasAuthenticationProvider ( ) ; p . setLoginConfig ( jaas . getLoginConfig ( ) ) ; p . setLoginContextName ( jaas . getLoginContextName ( ) ) ; p . setRefreshConfigurationOnStartup ( jaas . isRefreshConfigurationOnStartup ( ) ) ; p . afterPropertiesSet ( ) ; auth . authenticationProvider ( p ) ; } | Configure jaas authentication provider . |
18,310 | protected void configureEndpointAccessForStaticResources ( final ExpressionUrlAuthorizationConfigurer < HttpSecurity > . ExpressionInterceptUrlRegistry requests ) { requests . requestMatchers ( PathRequest . toStaticResources ( ) . atCommonLocations ( ) ) . permitAll ( ) ; requests . antMatchers ( "/resources/**" ) . permitAll ( ) . antMatchers ( "/static/**" ) . permitAll ( ) ; } | Configure endpoint access for static resources . |
18,311 | protected void configureEndpointAccessByFormLogin ( final ExpressionUrlAuthorizationConfigurer < HttpSecurity > . ExpressionInterceptUrlRegistry requests ) throws Exception { requests . and ( ) . formLogin ( ) . loginPage ( ENDPOINT_URL_ADMIN_FORM_LOGIN ) . permitAll ( ) ; } | Configure endpoint access by form login . |
18,312 | protected void configureEndpointAccess ( final HttpSecurity httpSecurity , final ExpressionUrlAuthorizationConfigurer < HttpSecurity > . ExpressionInterceptUrlRegistry requests , final ActuatorEndpointProperties . EndpointAccessLevel access , final ActuatorEndpointProperties properties , final EndpointRequest . EndpointRequestMatcher endpoint ) throws Exception { switch ( access ) { case AUTHORITY : configureEndpointAccessByAuthority ( requests , properties , endpoint ) ; configureEndpointAccessByFormLogin ( requests ) ; break ; case ROLE : configureEndpointAccessByRole ( requests , properties , endpoint ) ; configureEndpointAccessByFormLogin ( requests ) ; break ; case AUTHENTICATED : configureEndpointAccessAuthenticated ( requests , endpoint ) ; configureEndpointAccessByFormLogin ( requests ) ; break ; case IP_ADDRESS : configureEndpointAccessByIpAddress ( requests , properties , endpoint ) ; break ; case PERMIT : configureEndpointAccessPermitAll ( requests , endpoint ) ; break ; case ANONYMOUS : configureEndpointAccessAnonymously ( requests , endpoint ) ; break ; case DENY : default : configureEndpointAccessToDenyAll ( requests , endpoint ) ; break ; } } | Configure endpoint access . |
18,313 | public static Map < String , Object > getSystemInfo ( ) { val properties = System . getProperties ( ) ; val info = new LinkedHashMap < String , Object > ( SYSTEM_INFO_DEFAULT_SIZE ) ; info . put ( "CAS Version" , StringUtils . defaultString ( CasVersion . getVersion ( ) , "Not Available" ) ) ; info . put ( "CAS Commit Id" , StringUtils . defaultString ( CasVersion . getSpecificationVersion ( ) , "Not Available" ) ) ; info . put ( "CAS Build Date/Time" , CasVersion . getDateTime ( ) ) ; info . put ( "Spring Boot Version" , SpringBootVersion . getVersion ( ) ) ; info . put ( "Spring Version" , SpringVersion . getVersion ( ) ) ; info . put ( "Java Home" , properties . get ( "java.home" ) ) ; info . put ( "Java Vendor" , properties . get ( "java.vendor" ) ) ; info . put ( "Java Version" , properties . get ( "java.version" ) ) ; val runtime = Runtime . getRuntime ( ) ; info . put ( "JVM Free Memory" , FileUtils . byteCountToDisplaySize ( runtime . freeMemory ( ) ) ) ; info . put ( "JVM Maximum Memory" , FileUtils . byteCountToDisplaySize ( runtime . maxMemory ( ) ) ) ; info . put ( "JVM Total Memory" , FileUtils . byteCountToDisplaySize ( runtime . totalMemory ( ) ) ) ; info . put ( "JCE Installed" , StringUtils . capitalize ( BooleanUtils . toStringYesNo ( EncodingUtils . isJceInstalled ( ) ) ) ) ; info . put ( "OS Architecture" , properties . get ( "os.arch" ) ) ; info . put ( "OS Name" , properties . get ( "os.name" ) ) ; info . put ( "OS Version" , properties . get ( "os.version" ) ) ; info . put ( "OS Date/Time" , LocalDateTime . now ( ) ) ; info . put ( "OS Temp Directory" , FileUtils . getTempDirectoryPath ( ) ) ; injectUpdateInfoIntoBannerIfNeeded ( info ) ; return info ; } | Gets system info . |
18,314 | public static String getErrorMessage ( final com . authy . api . Error err ) { val builder = new StringBuilder ( ) ; if ( err != null ) { builder . append ( "Authy Error" ) ; if ( StringUtils . isNotBlank ( err . getCountryCode ( ) ) ) { builder . append ( ": Country Code: " ) . append ( err . getCountryCode ( ) ) ; } if ( StringUtils . isNotBlank ( err . getMessage ( ) ) ) { builder . append ( ": Message: " ) . append ( err . getMessage ( ) ) ; } } else { builder . append ( "An unknown error has occurred. Check your API key and URL settings." ) ; } return builder . toString ( ) ; } | Gets authy error message . |
18,315 | public User getOrCreateUser ( final Principal principal ) { val attributes = principal . getAttributes ( ) ; if ( ! attributes . containsKey ( this . mailAttribute ) ) { throw new IllegalArgumentException ( "No email address found for " + principal . getId ( ) ) ; } if ( ! attributes . containsKey ( this . phoneAttribute ) ) { throw new IllegalArgumentException ( "No phone number found for " + principal . getId ( ) ) ; } val email = attributes . get ( this . mailAttribute ) . get ( 0 ) . toString ( ) ; val phone = attributes . get ( this . phoneAttribute ) . get ( 0 ) . toString ( ) ; return this . authyUsers . createUser ( email , phone , this . countryCode ) ; } | Gets or create user . |
18,316 | private static String getJasyptParamFromEnv ( final Environment environment , final JasyptEncryptionParameters param ) { return environment . getProperty ( param . getPropertyName ( ) , param . getDefaultValue ( ) ) ; } | Gets jasypt param from env . |
18,317 | public void setAlgorithm ( final String alg ) { if ( StringUtils . isNotBlank ( alg ) ) { LOGGER . debug ( "Configured Jasypt algorithm [{}]" , alg ) ; jasyptInstance . setAlgorithm ( alg ) ; } } | Sets algorithm . |
18,318 | public void setPassword ( final String psw ) { if ( StringUtils . isNotBlank ( psw ) ) { LOGGER . debug ( "Configured Jasypt password" ) ; jasyptInstance . setPassword ( psw ) ; } } | Sets password . |
18,319 | public void setKeyObtentionIterations ( final String iter ) { if ( StringUtils . isNotBlank ( iter ) && NumberUtils . isCreatable ( iter ) ) { LOGGER . debug ( "Configured Jasypt iterations" ) ; jasyptInstance . setKeyObtentionIterations ( Integer . parseInt ( iter ) ) ; } } | Sets key obtention iterations . |
18,320 | public void setProviderName ( final String pName ) { if ( StringUtils . isNotBlank ( pName ) ) { LOGGER . debug ( "Configured Jasypt provider" ) ; this . jasyptInstance . setProviderName ( pName ) ; } } | Sets provider name . |
18,321 | public String encryptValue ( final String value ) { try { return encryptValuePropagateExceptions ( value ) ; } catch ( final Exception e ) { LOGGER . error ( "Could not encrypt value [{}]" , value , e ) ; } return null ; } | Encrypt value string . |
18,322 | public String decryptValue ( final String value ) { try { return decryptValuePropagateExceptions ( value ) ; } catch ( final Exception e ) { LOGGER . error ( "Could not decrypt value [{}]" , value , e ) ; } return null ; } | Decrypt value string . |
18,323 | @ ShellMethod ( key = "list-undocumented" , value = "List all CAS undocumented properties." ) public void listUndocumented ( ) { val repository = new CasConfigurationMetadataRepository ( ) ; repository . getRepository ( ) . getAllProperties ( ) . entrySet ( ) . stream ( ) . filter ( p -> p . getKey ( ) . startsWith ( "cas." ) && ( StringUtils . isBlank ( p . getValue ( ) . getShortDescription ( ) ) || StringUtils . isBlank ( p . getValue ( ) . getDescription ( ) ) ) ) . map ( Map . Entry :: getValue ) . sorted ( Comparator . comparing ( ConfigurationMetadataProperty :: getId ) ) . forEach ( p -> LOGGER . error ( "{} {} @ {}" , ERROR_MSG_PREFIX , p . getId ( ) , p . getType ( ) ) ) ; } | List undocumented settings . |
18,324 | public static String buildKey ( final RegisteredService service ) { return service . getId ( ) + ";" + service . getName ( ) + ';' + service . getServiceId ( ) ; } | Gets key . |
18,325 | public static void preparePeerEntitySamlEndpointContext ( final RequestAbstractType request , final MessageContext outboundContext , final SamlRegisteredServiceServiceProviderMetadataFacade adaptor , final String binding ) throws SamlException { val entityId = adaptor . getEntityId ( ) ; if ( ! adaptor . containsAssertionConsumerServices ( ) ) { throw new SamlException ( "No assertion consumer service could be found for entity " + entityId ) ; } val peerEntityContext = outboundContext . getSubcontext ( SAMLPeerEntityContext . class , true ) ; if ( peerEntityContext == null ) { throw new SamlException ( "SAMLPeerEntityContext could not be defined for entity " + entityId ) ; } peerEntityContext . setEntityId ( entityId ) ; val endpointContext = peerEntityContext . getSubcontext ( SAMLEndpointContext . class , true ) ; if ( endpointContext == null ) { throw new SamlException ( "SAMLEndpointContext could not be defined for entity " + entityId ) ; } val endpoint = determineEndpointForRequest ( request , adaptor , binding ) ; LOGGER . debug ( "Configured peer entity endpoint to be [{}] with binding [{}]" , endpoint . getLocation ( ) , endpoint . getBinding ( ) ) ; endpointContext . setEndpoint ( endpoint ) ; } | Prepare peer entity saml endpoint . |
18,326 | public static Endpoint determineEndpointForRequest ( final RequestAbstractType authnRequest , final SamlRegisteredServiceServiceProviderMetadataFacade adaptor , final String binding ) { var endpoint = ( Endpoint ) null ; if ( authnRequest instanceof LogoutRequest ) { endpoint = adaptor . getSingleLogoutService ( binding ) ; } else { val endpointReq = getAssertionConsumerServiceFromRequest ( authnRequest , binding ) ; endpoint = endpointReq == null ? adaptor . getAssertionConsumerService ( binding ) : endpointReq ; } if ( endpoint == null || StringUtils . isBlank ( endpoint . getBinding ( ) ) ) { throw new SamlException ( "Assertion consumer service does not define a binding" ) ; } val location = StringUtils . isBlank ( endpoint . getResponseLocation ( ) ) ? endpoint . getLocation ( ) : endpoint . getResponseLocation ( ) ; if ( StringUtils . isBlank ( location ) ) { throw new SamlException ( "Assertion consumer service does not define a target location" ) ; } return endpoint ; } | Determine assertion consumer service assertion consumer service . |
18,327 | @ SuppressFBWarnings ( "PRMC_POSSIBLY_REDUNDANT_METHOD_CALLS" ) public static MetadataResolver getMetadataResolverForAllSamlServices ( final ServicesManager servicesManager , final String entityID , final SamlRegisteredServiceCachingMetadataResolver resolver ) { val registeredServices = servicesManager . findServiceBy ( SamlRegisteredService . class :: isInstance ) ; val chainingMetadataResolver = new ChainingMetadataResolver ( ) ; val resolvers = registeredServices . stream ( ) . filter ( SamlRegisteredService . class :: isInstance ) . map ( SamlRegisteredService . class :: cast ) . map ( s -> SamlRegisteredServiceServiceProviderMetadataFacade . get ( resolver , s , entityID ) ) . filter ( Optional :: isPresent ) . map ( Optional :: get ) . map ( SamlRegisteredServiceServiceProviderMetadataFacade :: getMetadataResolver ) . collect ( Collectors . toList ( ) ) ; LOGGER . debug ( "Located [{}] metadata resolvers to match against [{}]" , resolvers , entityID ) ; chainingMetadataResolver . setResolvers ( resolvers ) ; chainingMetadataResolver . setId ( entityID ) ; chainingMetadataResolver . initialize ( ) ; return chainingMetadataResolver ; } | Gets chaining metadata resolver for all saml services . |
18,328 | public static AssertionConsumerService getAssertionConsumerServiceFor ( final AuthnRequest authnRequest , final ServicesManager servicesManager , final SamlRegisteredServiceCachingMetadataResolver resolver ) { try { val acs = new AssertionConsumerServiceBuilder ( ) . buildObject ( ) ; if ( authnRequest . getAssertionConsumerServiceIndex ( ) != null ) { val issuer = getIssuerFromSamlRequest ( authnRequest ) ; val samlResolver = getMetadataResolverForAllSamlServices ( servicesManager , issuer , resolver ) ; val criteriaSet = new CriteriaSet ( ) ; criteriaSet . add ( new EntityIdCriterion ( issuer ) ) ; criteriaSet . add ( new EntityRoleCriterion ( SPSSODescriptor . DEFAULT_ELEMENT_NAME ) ) ; criteriaSet . add ( new BindingCriterion ( CollectionUtils . wrap ( SAMLConstants . SAML2_POST_BINDING_URI ) ) ) ; val it = samlResolver . resolve ( criteriaSet ) ; it . forEach ( entityDescriptor -> { val spssoDescriptor = entityDescriptor . getSPSSODescriptor ( SAMLConstants . SAML20P_NS ) ; val acsEndpoints = spssoDescriptor . getAssertionConsumerServices ( ) ; if ( acsEndpoints . isEmpty ( ) ) { throw new IllegalArgumentException ( "Metadata resolved for entity id " + issuer + " has no defined ACS endpoints" ) ; } val acsIndex = authnRequest . getAssertionConsumerServiceIndex ( ) ; if ( acsIndex + 1 > acsEndpoints . size ( ) ) { throw new IllegalArgumentException ( "AssertionConsumerService index specified in the request " + acsIndex + " is invalid " + "since the total endpoints available to " + issuer + " is " + acsEndpoints . size ( ) ) ; } val foundAcs = acsEndpoints . get ( acsIndex ) ; acs . setBinding ( foundAcs . getBinding ( ) ) ; acs . setLocation ( foundAcs . getLocation ( ) ) ; acs . setResponseLocation ( foundAcs . getResponseLocation ( ) ) ; acs . setIndex ( acsIndex ) ; } ) ; } else { acs . setBinding ( authnRequest . getProtocolBinding ( ) ) ; acs . setLocation ( authnRequest . getAssertionConsumerServiceURL ( ) ) ; acs . setResponseLocation ( authnRequest . getAssertionConsumerServiceURL ( ) ) ; acs . setIndex ( 0 ) ; acs . setIsDefault ( Boolean . TRUE ) ; } LOGGER . debug ( "Resolved AssertionConsumerService from the request is [{}]" , acs ) ; if ( StringUtils . isBlank ( acs . getBinding ( ) ) ) { throw new SamlException ( "AssertionConsumerService has no protocol binding defined" ) ; } if ( StringUtils . isBlank ( acs . getLocation ( ) ) && StringUtils . isBlank ( acs . getResponseLocation ( ) ) ) { throw new SamlException ( "AssertionConsumerService has no location or response location defined" ) ; } return acs ; } catch ( final Exception e ) { throw new IllegalArgumentException ( new SamlException ( e . getMessage ( ) , e ) ) ; } } | Gets assertion consumer service for . |
18,329 | public static String getIssuerFromSamlObject ( final SAMLObject object ) { if ( object instanceof RequestAbstractType ) { return RequestAbstractType . class . cast ( object ) . getIssuer ( ) . getValue ( ) ; } if ( object instanceof StatusResponseType ) { return StatusResponseType . class . cast ( object ) . getIssuer ( ) . getValue ( ) ; } return null ; } | Gets issuer from saml object . |
18,330 | protected X509CRL fetchCRLFromLdap ( final Object r ) throws CertificateException , IOException , CRLException { try { val ldapURL = r . toString ( ) ; LOGGER . debug ( "Fetching CRL from ldap [{}]" , ldapURL ) ; val result = performLdapSearch ( ldapURL ) ; if ( result . getResultCode ( ) == ResultCode . SUCCESS ) { val entry = result . getResult ( ) . getEntry ( ) ; val attribute = entry . getAttribute ( this . certificateAttribute ) ; if ( attribute . isBinary ( ) ) { LOGGER . debug ( "Located entry [{}]. Retrieving first attribute [{}]" , entry , attribute ) ; return fetchX509CRLFromAttribute ( attribute ) ; } LOGGER . warn ( "Found certificate attribute [{}] but it is not marked as a binary attribute" , this . certificateAttribute ) ; } LOGGER . debug ( "Failed to execute the search [{}]" , result ) ; throw new CertificateException ( "Failed to establish a connection ldap and search." ) ; } catch ( final LdapException e ) { LOGGER . error ( e . getMessage ( ) , e ) ; throw new CertificateException ( e . getMessage ( ) ) ; } } | Downloads a CRL from given LDAP url . |
18,331 | protected X509CRL fetchX509CRLFromAttribute ( final LdapAttribute aval ) throws CertificateException , IOException , CRLException { if ( aval != null && aval . isBinary ( ) ) { val val = aval . getBinaryValue ( ) ; if ( val == null || val . length == 0 ) { throw new CertificateException ( "Empty attribute. Can not download CRL from ldap" ) ; } val decoded64 = EncodingUtils . decodeBase64 ( val ) ; if ( decoded64 == null ) { throw new CertificateException ( "Could not decode the attribute value to base64" ) ; } LOGGER . debug ( "Retrieved CRL from ldap as byte array decoded in base64. Fetching..." ) ; return super . fetch ( new ByteArrayResource ( decoded64 ) ) ; } throw new CertificateException ( "Attribute not found. Can not retrieve CRL" ) ; } | Gets x509 cRL from attribute . Retrieves the binary attribute value decodes it to base64 and fetches it as a byte - array resource . |
18,332 | protected Response < SearchResult > performLdapSearch ( final String ldapURL ) throws LdapException { val connectionFactory = prepareConnectionFactory ( ldapURL ) ; return this . searchExecutor . search ( connectionFactory ) ; } | Executes an LDAP search against the supplied URL . |
18,333 | protected ConnectionFactory prepareConnectionFactory ( final String ldapURL ) { val cc = ConnectionConfig . newConnectionConfig ( this . connectionConfig ) ; cc . setLdapUrl ( ldapURL ) ; return new DefaultConnectionFactory ( cc ) ; } | Prepare a new LDAP connection . |
18,334 | public T getProvider ( final String id ) { return ( T ) beanFactory . getBean ( providerFactory . beanName ( id ) ) ; } | Returns the provider assigned to the passed id . |
18,335 | public static IPersonAttributeDao newStubAttributeRepository ( final PrincipalAttributesProperties p ) { val dao = new NamedStubPersonAttributeDao ( ) ; val pdirMap = new LinkedHashMap < String , List < Object > > ( ) ; val stub = p . getStub ( ) ; stub . getAttributes ( ) . forEach ( ( key , value ) -> { val vals = StringUtils . commaDelimitedListToStringArray ( value ) ; pdirMap . put ( key , Arrays . stream ( vals ) . collect ( Collectors . toList ( ) ) ) ; } ) ; dao . setBackingMap ( pdirMap ) ; if ( StringUtils . hasText ( stub . getId ( ) ) ) { dao . setId ( stub . getId ( ) ) ; } return dao ; } | New attribute repository person attribute dao . |
18,336 | public static Duration newDuration ( final String length ) { if ( NumberUtils . isCreatable ( length ) ) { return Duration . ofSeconds ( Long . parseLong ( length ) ) ; } return Duration . parse ( length ) ; } | New duration . If the provided length is duration it will be parsed accordingly or if it s a numeric value it will be pared as a duration assuming it s provided as seconds . |
18,337 | public static String getGrouperGroupAttribute ( final GrouperGroupField groupField , final WsGroup group ) { switch ( groupField ) { case DISPLAY_EXTENSION : return group . getDisplayExtension ( ) ; case DISPLAY_NAME : return group . getDisplayName ( ) ; case EXTENSION : return group . getExtension ( ) ; case NAME : default : return group . getName ( ) ; } } | Construct grouper group attribute . This is the name of every individual group attribute transformed into a CAS attribute value . |
18,338 | public Collection < WsGetGroupsResult > getGroupsForSubjectId ( final String subjectId ) { try { val groupsClient = new GcGetGroups ( ) . addSubjectId ( subjectId ) ; val results = groupsClient . execute ( ) . getResults ( ) ; if ( results == null || results . length == 0 ) { LOGGER . warn ( "Subject id [{}] could not be located." , subjectId ) ; return new ArrayList < > ( 0 ) ; } LOGGER . debug ( "Found [{}] groups for [{}]" , results . length , subjectId ) ; return CollectionUtils . wrapList ( results ) ; } catch ( final Exception e ) { LOGGER . warn ( "Grouper WS did not respond successfully. Ensure your credentials are correct " + ", the url endpoint for Grouper WS is correctly configured and the subject [{}] exists in Grouper." , subjectId , e ) ; } return new ArrayList < > ( 0 ) ; } | Gets groups for subject id . |
18,339 | public BaseHttpServletRequestXMLMessageDecoder getInstance ( final HttpMethod method ) { val decoder = get ( method ) ; return ( BaseHttpServletRequestXMLMessageDecoder ) BeanUtils . cloneBean ( decoder ) ; } | Gets a cloned instance of the decoder . Decoders are initialized once at configuration and then re - created on demand so they can initialized via OpenSAML again for new incoming requests . |
18,340 | @ View ( name = "by_uid_otp" , map = "function(doc) { if(doc.token && doc.userId) { emit([doc.userId, doc.token], doc) } }" ) public CouchDbGoogleAuthenticatorToken findOneByUidForOtp ( final String uid , final Integer otp ) { val view = createQuery ( "by_uid_otp" ) . key ( ComplexKey . of ( uid , otp ) ) . limit ( 1 ) ; return db . queryView ( view , CouchDbGoogleAuthenticatorToken . class ) . stream ( ) . findFirst ( ) . orElse ( null ) ; } | Find first by uid otp pair . |
18,341 | @ View ( name = "by_issued_date_time" , map = "function(doc) { if(doc.token && doc.userId) { emit(doc.issuedDateTime, doc) } }" ) public Collection < CouchDbGoogleAuthenticatorToken > findByIssuedDateTimeBefore ( final LocalDateTime localDateTime ) { val view = createQuery ( "by_issued_date_time" ) . endKey ( localDateTime ) ; return db . queryView ( view , CouchDbGoogleAuthenticatorToken . class ) ; } | Find by issued date . |
18,342 | @ View ( name = "by_userId" , map = "function(doc) { if(doc.token && doc.userId) { emit(doc.userId, doc) } }" ) public List < CouchDbGoogleAuthenticatorToken > findByUserId ( final String userId ) { return queryView ( "by_userId" , userId ) ; } | Find tokens by user id . |
18,343 | @ View ( name = "count_by_userId" , map = "function(doc) { if(doc.token && doc.userId) { emit(doc.userId, doc) } }" , reduce = "_count" ) public long countByUserId ( final String userId ) { val view = createQuery ( "count_by_userId" ) . key ( userId ) ; val rows = db . queryView ( view ) . getRows ( ) ; if ( rows . isEmpty ( ) ) { return 0 ; } return rows . get ( 0 ) . getValueAsInt ( ) ; } | Token count for a user . |
18,344 | @ View ( name = "count" , map = "function(doc) { if(doc.token && doc.userId) { emit(doc._id, doc) } }" , reduce = "_count" ) public long count ( ) { val rows = db . queryView ( createQuery ( "count" ) ) . getRows ( ) ; if ( rows . isEmpty ( ) ) { return 0 ; } return rows . get ( 0 ) . getValueAsInt ( ) ; } | Total number of tokens stored . |
18,345 | @ UpdateHandler ( name = "delete_token" , file = "CouchDbOneTimeToken_delete.js" ) public void deleteToken ( final CouchDbGoogleAuthenticatorToken token ) { db . callUpdateHandler ( stdDesignDocumentId , "delete_token" , token . getCid ( ) , null ) ; } | Delete record ignoring rev . |
18,346 | @ View ( name = "by_uid_otp" , map = "function(doc) { if(doc.token && doc.userId) { emit([doc.userId, doc.token], doc) } }" ) public List < CouchDbGoogleAuthenticatorToken > findByUidForOtp ( final String uid , final Integer otp ) { val view = createQuery ( "by_uid_otp" ) . key ( ComplexKey . of ( uid , otp ) ) ; return db . queryView ( view , CouchDbGoogleAuthenticatorToken . class ) ; } | Find all by uid otp pair . |
18,347 | @ View ( name = "by_token" , map = "function(doc) { if(doc.token && doc.userId) { emit(doc.token, doc) } }" ) public List < CouchDbGoogleAuthenticatorToken > findByToken ( final Integer otp ) { return queryView ( "by_token" , otp ) ; } | Find by token . |
18,348 | protected String getJwtId ( final TicketGrantingTicket tgt ) { val oAuthCallbackUrl = getConfigurationContext ( ) . getCasProperties ( ) . getServer ( ) . getPrefix ( ) + OAuth20Constants . BASE_OAUTH20_URL + '/' + OAuth20Constants . CALLBACK_AUTHORIZE_URL_DEFINITION ; val oAuthServiceTicket = Stream . concat ( tgt . getServices ( ) . entrySet ( ) . stream ( ) , tgt . getProxyGrantingTickets ( ) . entrySet ( ) . stream ( ) ) . filter ( e -> { val service = getConfigurationContext ( ) . getServicesManager ( ) . findServiceBy ( e . getValue ( ) ) ; return service != null && service . getServiceId ( ) . equals ( oAuthCallbackUrl ) ; } ) . findFirst ( ) ; if ( oAuthServiceTicket . isEmpty ( ) ) { LOGGER . trace ( "Cannot find ticket issued to [{}] as part of the authentication context" , oAuthCallbackUrl ) ; return tgt . getId ( ) ; } return oAuthServiceTicket . get ( ) . getKey ( ) ; } | Gets oauth service ticket . |
18,349 | protected String generateAccessTokenHash ( final AccessToken accessTokenId , final OidcRegisteredService service ) { val alg = getConfigurationContext ( ) . getIdTokenSigningAndEncryptionService ( ) . getJsonWebKeySigningAlgorithm ( service ) ; val tokenBytes = accessTokenId . getId ( ) . getBytes ( StandardCharsets . UTF_8 ) ; if ( AlgorithmIdentifiers . NONE . equalsIgnoreCase ( alg ) ) { LOGGER . debug ( "Signing algorithm specified by service [{}] is unspecified" , service . getServiceId ( ) ) ; return EncodingUtils . encodeUrlSafeBase64 ( tokenBytes ) ; } val hashAlg = getSigningHashAlgorithm ( service ) ; LOGGER . debug ( "Digesting access token hash via algorithm [{}]" , hashAlg ) ; val digested = DigestUtils . rawDigest ( hashAlg , tokenBytes ) ; val hashBytesLeftHalf = Arrays . copyOf ( digested , digested . length / 2 ) ; return EncodingUtils . encodeUrlSafeBase64 ( hashBytesLeftHalf ) ; } | Generate access token hash string . |
18,350 | protected String getSigningHashAlgorithm ( final OidcRegisteredService service ) { val alg = getConfigurationContext ( ) . getIdTokenSigningAndEncryptionService ( ) . getJsonWebKeySigningAlgorithm ( service ) ; LOGGER . debug ( "Signing algorithm specified by service [{}] is [{}]" , service . getServiceId ( ) , alg ) ; if ( AlgorithmIdentifiers . RSA_USING_SHA512 . equalsIgnoreCase ( alg ) ) { return MessageDigestAlgorithms . SHA_512 ; } if ( AlgorithmIdentifiers . RSA_USING_SHA384 . equalsIgnoreCase ( alg ) ) { return MessageDigestAlgorithms . SHA_384 ; } if ( AlgorithmIdentifiers . RSA_USING_SHA256 . equalsIgnoreCase ( alg ) ) { return MessageDigestAlgorithms . SHA_256 ; } throw new IllegalArgumentException ( "Could not determine the hash algorithm for the id token issued to service " + service . getServiceId ( ) ) ; } | Gets signing hash algorithm . |
18,351 | public Map < String , Object > handle ( 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 principalId = registeredService . getUsernameAttributeProvider ( ) . resolveUsername ( principal , selectedService , registeredService ) ; val modifiedPrincipal = this . principalFactory . createPrincipal ( principalId , attributesToRelease ) ; val builder = DefaultAuthenticationBuilder . newInstance ( authentication ) ; builder . setPrincipal ( modifiedPrincipal ) ; val finalAuthentication = builder . build ( ) ; val samlResponse = this . samlResponseBuilder . createResponse ( selectedService . getId ( ) , selectedService ) ; samlResponseBuilder . prepareSuccessfulResponse ( samlResponse , selectedService , finalAuthentication , principal , finalAuthentication . getAttributes ( ) , principal . getAttributes ( ) ) ; val resValidation = new LinkedHashMap < String , Object > ( ) ; val encoded = SamlUtils . transformSamlObject ( this . openSamlConfigBean , samlResponse ) . toString ( ) ; resValidation . put ( CasViewConstants . MODEL_ATTRIBUTE_NAME_ASSERTION , encoded ) ; resValidation . put ( CasViewConstants . MODEL_ATTRIBUTE_NAME_SERVICE , selectedService ) ; resValidation . put ( "registeredService" , registeredService ) ; return resValidation ; } | Handle validation request and produce saml1 payload . |
18,352 | private CloseableHttpClient buildHttpClient ( ) { val plainSocketFactory = PlainConnectionSocketFactory . getSocketFactory ( ) ; val registry = RegistryBuilder . < ConnectionSocketFactory > create ( ) . register ( "http" , plainSocketFactory ) . register ( "https" , this . sslSocketFactory ) . build ( ) ; val connectionManager = new PoolingHttpClientConnectionManager ( registry ) ; connectionManager . setMaxTotal ( this . maxPooledConnections ) ; connectionManager . setDefaultMaxPerRoute ( this . maxConnectionsPerRoute ) ; connectionManager . setValidateAfterInactivity ( DEFAULT_TIMEOUT ) ; val httpHost = new HttpHost ( InetAddress . getLocalHost ( ) ) ; val httpRoute = new HttpRoute ( httpHost ) ; connectionManager . setMaxPerRoute ( httpRoute , MAX_CONNECTIONS_PER_ROUTE ) ; val requestConfig = RequestConfig . custom ( ) . setSocketTimeout ( this . readTimeout ) . setConnectTimeout ( ( int ) this . connectionTimeout ) . setConnectionRequestTimeout ( ( int ) this . connectionTimeout ) . setCircularRedirectsAllowed ( this . circularRedirectsAllowed ) . setRedirectsEnabled ( this . redirectsEnabled ) . setAuthenticationEnabled ( this . authenticationEnabled ) . build ( ) ; val builder = HttpClients . custom ( ) . setConnectionManager ( connectionManager ) . setDefaultRequestConfig ( requestConfig ) . setSSLSocketFactory ( this . sslSocketFactory ) . setSSLHostnameVerifier ( this . hostnameVerifier ) . setRedirectStrategy ( this . redirectionStrategy ) . setDefaultCredentialsProvider ( this . credentialsProvider ) . setDefaultCookieStore ( this . cookieStore ) . setConnectionReuseStrategy ( this . connectionReuseStrategy ) . setConnectionBackoffStrategy ( this . connectionBackoffStrategy ) . setServiceUnavailableRetryStrategy ( this . serviceUnavailableRetryStrategy ) . setProxyAuthenticationStrategy ( this . proxyAuthenticationStrategy ) . setDefaultHeaders ( this . defaultHeaders ) . useSystemProperties ( ) ; return builder . build ( ) ; } | Build a HTTP client based on the current properties . |
18,353 | protected String getAlternatePrincipal ( final X509Certificate certificate ) { if ( alternatePrincipalAttribute == null ) { return null ; } val attributes = extractPersonAttributes ( certificate ) ; val attribute = attributes . get ( alternatePrincipalAttribute ) ; if ( attribute == null ) { LOGGER . debug ( "Attempt to get alternate principal with attribute [{}] was unsuccessful." , alternatePrincipalAttribute ) ; return null ; } val optionalAttribute = CollectionUtils . firstElement ( attribute ) ; if ( optionalAttribute . isEmpty ( ) ) { LOGGER . debug ( "Alternate attribute list for [{}] was empty." , alternatePrincipalAttribute ) ; return null ; } val alternatePrincipal = optionalAttribute . get ( ) . toString ( ) ; if ( StringUtils . isNotEmpty ( alternatePrincipal ) ) { LOGGER . debug ( "Using alternate principal attribute [{}]" , alternatePrincipal ) ; return alternatePrincipal ; } LOGGER . debug ( "Returning null principal id..." ) ; return null ; } | Get alternate principal if alternate attribute configured . |
18,354 | protected Map < String , List < Object > > extractPersonAttributes ( final X509Certificate certificate ) { val attributes = new LinkedHashMap < String , List < Object > > ( ) ; if ( certificate != null ) { if ( StringUtils . isNotBlank ( certificate . getSigAlgOID ( ) ) ) { attributes . put ( "sigAlgOid" , CollectionUtils . wrapList ( certificate . getSigAlgOID ( ) ) ) ; } val subjectDn = certificate . getSubjectDN ( ) ; if ( subjectDn != null ) { attributes . put ( "subjectDn" , CollectionUtils . wrapList ( subjectDn . getName ( ) ) ) ; } val subjectPrincipal = certificate . getSubjectX500Principal ( ) ; if ( subjectPrincipal != null ) { attributes . put ( "subjectX500Principal" , CollectionUtils . wrapList ( subjectPrincipal . getName ( ) ) ) ; } try { val rfc822Email = getRFC822EmailAddress ( certificate . getSubjectAlternativeNames ( ) ) ; if ( rfc822Email != null ) { attributes . put ( "x509Rfc822Email" , CollectionUtils . wrapList ( rfc822Email ) ) ; } } catch ( final CertificateParsingException e ) { LOGGER . warn ( "Error parsing subject alternative names to get rfc822 email [{}]" , e . getMessage ( ) ) ; } } return attributes ; } | Get additional attributes from the certificate . |
18,355 | protected String getRFC822EmailAddress ( final Collection < List < ? > > subjectAltNames ) { if ( subjectAltNames == null ) { return null ; } Optional < List < ? > > email = subjectAltNames . stream ( ) . filter ( s -> s . size ( ) == 2 && ( Integer ) s . get ( 0 ) == SAN_RFC822_EMAIL_TYPE ) . findFirst ( ) ; return email . map ( objects -> ( String ) objects . get ( 1 ) ) . orElse ( null ) ; } | Get Email Address . |
18,356 | public CouchDbSamlIdPMetadataDocument merge ( final SamlIdPMetadataDocument doc ) { setId ( doc . getId ( ) ) ; setMetadata ( doc . getMetadata ( ) ) ; setSigningCertificate ( doc . getSigningCertificate ( ) ) ; setSigningKey ( doc . getSigningKey ( ) ) ; setEncryptionCertificate ( doc . getEncryptionCertificate ( ) ) ; setEncryptionKey ( doc . getEncryptionKey ( ) ) ; return this ; } | Merge another doc into this one . |
18,357 | protected void registerMultifactorFlowDefinitionIntoLoginFlowRegistry ( final FlowDefinitionRegistry sourceRegistry ) { val flowIds = sourceRegistry . getFlowDefinitionIds ( ) ; for ( val flowId : flowIds ) { val definition = sourceRegistry . getFlowDefinition ( flowId ) ; if ( definition != null ) { LOGGER . trace ( "Registering flow definition [{}]" , flowId ) ; this . loginFlowDefinitionRegistry . registerFlowDefinition ( definition ) ; } } } | Register flow definition into login flow registry . |
18,358 | protected void augmentMultifactorProviderFlowRegistry ( final FlowDefinitionRegistry mfaProviderFlowRegistry ) { val flowIds = mfaProviderFlowRegistry . getFlowDefinitionIds ( ) ; Arrays . stream ( flowIds ) . forEach ( id -> { val flow = ( Flow ) mfaProviderFlowRegistry . getFlowDefinition ( id ) ; if ( flow != null && containsFlowState ( flow , CasWebflowConstants . STATE_ID_REAL_SUBMIT ) ) { val states = getCandidateStatesForMultifactorAuthentication ( ) ; states . forEach ( s -> { val state = getState ( flow , s ) ; ensureEndStateTransitionExists ( state , flow , CasWebflowConstants . TRANSITION_ID_SUCCESS , CasWebflowConstants . STATE_ID_SUCCESS ) ; ensureEndStateTransitionExists ( state , flow , CasWebflowConstants . TRANSITION_ID_SUCCESS_WITH_WARNINGS , CasWebflowConstants . TRANSITION_ID_SUCCESS_WITH_WARNINGS ) ; ensureEndStateTransitionExists ( state , flow , CasWebflowConstants . TRANSITION_ID_UNAVAILABLE , CasWebflowConstants . STATE_ID_MFA_UNAVAILABLE ) ; ensureEndStateTransitionExists ( state , flow , CasWebflowConstants . TRANSITION_ID_DENY , CasWebflowConstants . STATE_ID_MFA_DENIED ) ; } ) ; } } ) ; } | Augment mfa provider flow registry . |
18,359 | protected void registerMultifactorTrustedAuthentication ( final FlowDefinitionRegistry flowDefinitionRegistry ) { validateFlowDefinitionConfiguration ( flowDefinitionRegistry ) ; LOGGER . debug ( "Flow definitions found in the registry are [{}]" , ( Object [ ] ) flowDefinitionRegistry . getFlowDefinitionIds ( ) ) ; val flowId = Arrays . stream ( flowDefinitionRegistry . getFlowDefinitionIds ( ) ) . findFirst ( ) . get ( ) ; LOGGER . debug ( "Processing flow definition [{}]" , flowId ) ; val flow = ( Flow ) flowDefinitionRegistry . getFlowDefinition ( flowId ) ; val state = getState ( flow , CasWebflowConstants . STATE_ID_INIT_LOGIN_FORM , ActionState . class ) ; val transition = ( Transition ) state . getTransition ( CasWebflowConstants . TRANSITION_ID_SUCCESS ) ; val targetStateId = transition . getTargetStateId ( ) ; transition . setTargetStateResolver ( new DefaultTargetStateResolver ( CasWebflowConstants . STATE_ID_VERIFY_TRUSTED_DEVICE ) ) ; val verifyAction = createActionState ( flow , CasWebflowConstants . STATE_ID_VERIFY_TRUSTED_DEVICE , createEvaluateAction ( MFA_VERIFY_TRUST_ACTION_BEAN_ID ) ) ; if ( enableDeviceRegistration ) { createTransitionForState ( verifyAction , CasWebflowConstants . TRANSITION_ID_YES , CasWebflowConstants . STATE_ID_FINISH_MFA_TRUSTED_AUTH ) ; } else { createTransitionForState ( verifyAction , CasWebflowConstants . TRANSITION_ID_YES , CasWebflowConstants . STATE_ID_REAL_SUBMIT ) ; } createTransitionForState ( verifyAction , CasWebflowConstants . TRANSITION_ID_NO , targetStateId ) ; createDecisionState ( flow , CasWebflowConstants . DECISION_STATE_REQUIRE_REGISTRATION , isDeviceRegistrationRequired ( ) , CasWebflowConstants . VIEW_ID_REGISTER_DEVICE , CasWebflowConstants . STATE_ID_REAL_SUBMIT ) ; val submit = getState ( flow , CasWebflowConstants . STATE_ID_REAL_SUBMIT , ActionState . class ) ; val success = ( Transition ) submit . getTransition ( CasWebflowConstants . TRANSITION_ID_SUCCESS ) ; if ( enableDeviceRegistration ) { success . setTargetStateResolver ( new DefaultTargetStateResolver ( CasWebflowConstants . VIEW_ID_REGISTER_DEVICE ) ) ; } else { success . setTargetStateResolver ( new DefaultTargetStateResolver ( CasWebflowConstants . STATE_ID_REGISTER_TRUSTED_DEVICE ) ) ; } val viewRegister = createViewState ( flow , CasWebflowConstants . VIEW_ID_REGISTER_DEVICE , "casMfaRegisterDeviceView" ) ; val viewRegisterTransition = createTransition ( CasWebflowConstants . TRANSITION_ID_SUBMIT , CasWebflowConstants . STATE_ID_REGISTER_TRUSTED_DEVICE ) ; viewRegister . getTransitionSet ( ) . add ( viewRegisterTransition ) ; val registerAction = createActionState ( flow , CasWebflowConstants . STATE_ID_REGISTER_TRUSTED_DEVICE , createEvaluateAction ( MFA_SET_TRUST_ACTION_BEAN_ID ) ) ; createStateDefaultTransition ( registerAction , CasWebflowConstants . STATE_ID_SUCCESS ) ; if ( submit . getActionList ( ) . size ( ) == 0 ) { throw new IllegalArgumentException ( "There are no actions defined for the final submission event of " + flowId ) ; } val act = submit . getActionList ( ) . iterator ( ) . next ( ) ; val finishMfaTrustedAuth = createActionState ( flow , CasWebflowConstants . STATE_ID_FINISH_MFA_TRUSTED_AUTH , act ) ; val finishedTransition = createTransition ( CasWebflowConstants . TRANSITION_ID_SUCCESS , CasWebflowConstants . STATE_ID_SUCCESS ) ; finishMfaTrustedAuth . getTransitionSet ( ) . add ( finishedTransition ) ; createStateDefaultTransition ( finishMfaTrustedAuth , CasWebflowConstants . STATE_ID_SUCCESS ) ; } | Register multifactor trusted authentication into webflow . |
18,360 | protected boolean shouldSkipInterruptForRegisteredService ( final RegisteredService registeredService ) { if ( registeredService != null ) { LOGGER . debug ( "Checking interrupt rules for service [{}]" , registeredService . getName ( ) ) ; if ( RegisteredServiceProperties . SKIP_INTERRUPT_NOTIFICATIONS . isAssignedTo ( registeredService ) ) { LOGGER . debug ( "Service [{}] is set to skip interrupt notifications" , registeredService . getName ( ) ) ; return true ; } LOGGER . debug ( "Service [{}] is set to not skip interrupt notifications" , registeredService . getName ( ) ) ; } else { LOGGER . debug ( "No service was found in the request context. Proceeding as usual..." ) ; } return false ; } | Should skip interrupt for registered service . |
18,361 | public static String sanitize ( final String msg ) { var modifiedMessage = msg ; if ( StringUtils . isNotBlank ( msg ) && ! Boolean . getBoolean ( "CAS_TICKET_ID_SANITIZE_SKIP" ) ) { val matcher = TICKET_ID_PATTERN . matcher ( msg ) ; while ( matcher . find ( ) ) { val match = matcher . group ( ) ; val group = matcher . group ( 1 ) ; val length = group . length ( ) ; var replaceLength = length - VISIBLE_TAIL_LENGTH - ( HOST_NAME_LENGTH + 1 ) ; if ( replaceLength <= 0 ) { replaceLength = length ; } val newId = match . replace ( group . substring ( 0 , replaceLength ) , "*" . repeat ( OBFUSCATION_LENGTH ) ) ; modifiedMessage = modifiedMessage . replaceAll ( match , newId ) ; } } return modifiedMessage ; } | Remove ticket id from the message . |
18,362 | protected Status status ( final CacheStatistics statistics ) { if ( statistics . getEvictions ( ) > 0 && statistics . getEvictions ( ) > evictionThreshold ) { return new Status ( "WARN" ) ; } if ( statistics . getPercentFree ( ) > 0 && statistics . getPercentFree ( ) < threshold ) { return Status . OUT_OF_SERVICE ; } return Status . UP ; } | Computes the status code for a given set of cache statistics . |
18,363 | protected Event handleException ( final J2EContext webContext , final BaseClient < Credentials , CommonProfile > client , final Exception e ) { if ( e instanceof RequestSloException ) { try { webContext . getResponse ( ) . sendRedirect ( "logout" ) ; } catch ( final IOException ioe ) { throw new IllegalArgumentException ( "Unable to call logout" , ioe ) ; } return stopWebflow ( ) ; } val msg = String . format ( "Delegated authentication has failed with client %s" , client . getName ( ) ) ; LOGGER . error ( msg , e ) ; throw new IllegalArgumentException ( msg ) ; } | Handle the thrown exception . |
18,364 | protected Credentials getCredentialsFromDelegatedClient ( final J2EContext webContext , final BaseClient < Credentials , CommonProfile > client ) { val credentials = client . getCredentials ( webContext ) ; LOGGER . debug ( "Retrieved credentials from client as [{}]" , credentials ) ; if ( credentials == null ) { throw new IllegalArgumentException ( "Unable to determine credentials from the context with client " + client . getName ( ) ) ; } return credentials ; } | Gets credentials from delegated client . |
18,365 | protected BaseClient < Credentials , CommonProfile > findDelegatedClientByName ( final HttpServletRequest request , final String clientName , final Service service ) { val client = ( BaseClient < Credentials , CommonProfile > ) this . clients . findClient ( clientName ) ; LOGGER . debug ( "Delegated authentication client is [{}] with service [{}}" , client , service ) ; if ( service != null ) { request . setAttribute ( CasProtocolConstants . PARAMETER_SERVICE , service . getId ( ) ) ; if ( ! isDelegatedClientAuthorizedForService ( client , service ) ) { LOGGER . warn ( "Delegated client [{}] is not authorized by service [{}]" , client , service ) ; throw new UnauthorizedServiceException ( UnauthorizedServiceException . CODE_UNAUTHZ_SERVICE , StringUtils . EMPTY ) ; } } return client ; } | Find delegated client by name base client . |
18,366 | protected void prepareForLoginPage ( final RequestContext context ) { val currentService = WebUtils . getService ( context ) ; val service = authenticationRequestServiceSelectionStrategies . resolveService ( currentService , WebApplicationService . class ) ; val request = WebUtils . getHttpServletRequestFromExternalWebflowContext ( context ) ; val response = WebUtils . getHttpServletResponseFromExternalWebflowContext ( context ) ; val webContext = new J2EContext ( request , response , this . sessionStore ) ; val urls = new LinkedHashSet < ProviderLoginPageConfiguration > ( ) ; this . clients . findAllClients ( ) . stream ( ) . filter ( client -> client instanceof IndirectClient && isDelegatedClientAuthorizedForService ( client , service ) ) . map ( IndirectClient . class :: cast ) . forEach ( client -> { try { val provider = buildProviderConfiguration ( client , webContext , currentService ) ; provider . ifPresent ( p -> { urls . add ( p ) ; if ( p . isAutoRedirect ( ) ) { WebUtils . putDelegatedAuthenticationProviderPrimary ( context , p ) ; } } ) ; } catch ( final Exception e ) { LOGGER . error ( "Cannot process client [{}]" , client , e ) ; } } ) ; if ( ! urls . isEmpty ( ) ) { context . getFlowScope ( ) . put ( FLOW_ATTRIBUTE_PROVIDER_URLS , urls ) ; } else if ( response . getStatus ( ) != HttpStatus . UNAUTHORIZED . value ( ) ) { LOGGER . warn ( "No delegated authentication providers could be determined based on the provided configuration. " + "Either no clients are configured, or the current access strategy rules prohibit CAS from using authentication providers for this request." ) ; } } | Prepare the data for the login page . |
18,367 | protected Optional < ProviderLoginPageConfiguration > buildProviderConfiguration ( final IndirectClient client , final WebContext webContext , final WebApplicationService service ) { val name = client . getName ( ) ; val matcher = PAC4J_CLIENT_SUFFIX_PATTERN . matcher ( client . getClass ( ) . getSimpleName ( ) ) ; val type = matcher . replaceAll ( StringUtils . EMPTY ) . toLowerCase ( ) ; val uriBuilder = UriComponentsBuilder . fromUriString ( DelegatedClientNavigationController . ENDPOINT_REDIRECT ) . queryParam ( Pac4jConstants . DEFAULT_CLIENT_NAME_PARAMETER , name ) ; if ( service != null ) { val sourceParam = service . getSource ( ) ; val serviceParam = service . getOriginalUrl ( ) ; if ( StringUtils . isNotBlank ( sourceParam ) && StringUtils . isNotBlank ( serviceParam ) ) { uriBuilder . queryParam ( sourceParam , serviceParam ) ; } } val methodParam = webContext . getRequestParameter ( CasProtocolConstants . PARAMETER_METHOD ) ; if ( StringUtils . isNotBlank ( methodParam ) ) { uriBuilder . queryParam ( CasProtocolConstants . PARAMETER_METHOD , methodParam ) ; } val localeParam = webContext . getRequestParameter ( this . localeParamName ) ; if ( StringUtils . isNotBlank ( localeParam ) ) { uriBuilder . queryParam ( this . localeParamName , localeParam ) ; } val themeParam = webContext . getRequestParameter ( this . themeParamName ) ; if ( StringUtils . isNotBlank ( themeParam ) ) { uriBuilder . queryParam ( this . themeParamName , themeParam ) ; } val redirectUrl = uriBuilder . toUriString ( ) ; val autoRedirect = ( Boolean ) client . getCustomProperties ( ) . getOrDefault ( ClientCustomPropertyConstants . CLIENT_CUSTOM_PROPERTY_AUTO_REDIRECT , Boolean . FALSE ) ; val p = new ProviderLoginPageConfiguration ( name , redirectUrl , type , getCssClass ( name ) , autoRedirect ) ; return Optional . of ( p ) ; } | Build provider configuration optional . |
18,368 | protected String getCssClass ( final String name ) { var computedCssClass = "fa fa-lock" ; if ( StringUtils . isNotBlank ( name ) ) { computedCssClass = computedCssClass . concat ( ' ' + PAC4J_CLIENT_CSS_CLASS_SUBSTITUTION_PATTERN . matcher ( name ) . replaceAll ( "-" ) ) ; } LOGGER . debug ( "CSS class for [{}] is [{}]" , name , computedCssClass ) ; return computedCssClass ; } | Get a valid CSS class for the given provider name . |
18,369 | protected boolean isDelegatedClientAuthorizedForService ( final Client client , final Service service ) { if ( service == null || StringUtils . isBlank ( service . getId ( ) ) ) { LOGGER . debug ( "Can not evaluate delegated authentication policy since no service was provided in the request while processing client [{}]" , client ) ; return true ; } val registeredService = this . servicesManager . findServiceBy ( service ) ; if ( registeredService == null || ! registeredService . getAccessStrategy ( ) . isServiceAccessAllowed ( ) ) { LOGGER . warn ( "Service access for [{}] is denied" , registeredService ) ; return false ; } LOGGER . trace ( "Located registered service definition [{}] matching [{}]" , registeredService , service ) ; val context = AuditableContext . builder ( ) . registeredService ( registeredService ) . properties ( CollectionUtils . wrap ( Client . class . getSimpleName ( ) , client . getName ( ) ) ) . build ( ) ; val result = delegatedAuthenticationPolicyEnforcer . execute ( context ) ; if ( ! result . isExecutionFailure ( ) ) { LOGGER . debug ( "Delegated authentication policy for [{}] allows for using client [{}]" , registeredService , client ) ; return true ; } LOGGER . warn ( "Delegated authentication policy for [{}] refuses access to client [{}]" , registeredService . getServiceId ( ) , client ) ; return false ; } | Is delegated client authorized for service boolean . |
18,370 | public static Optional < ModelAndView > hasDelegationRequestFailed ( final HttpServletRequest request , final int status ) { val params = request . getParameterMap ( ) ; if ( Stream . of ( "error" , "error_code" , "error_description" , "error_message" ) . anyMatch ( params :: containsKey ) ) { val model = new HashMap < String , Object > ( ) ; if ( params . containsKey ( "error_code" ) ) { model . put ( "code" , StringEscapeUtils . escapeHtml4 ( request . getParameter ( "error_code" ) ) ) ; } else { model . put ( "code" , status ) ; } model . put ( "error" , StringEscapeUtils . escapeHtml4 ( request . getParameter ( "error" ) ) ) ; model . put ( "reason" , StringEscapeUtils . escapeHtml4 ( request . getParameter ( "error_reason" ) ) ) ; if ( params . containsKey ( "error_description" ) ) { model . put ( "description" , StringEscapeUtils . escapeHtml4 ( request . getParameter ( "error_description" ) ) ) ; } else if ( params . containsKey ( "error_message" ) ) { model . put ( "description" , StringEscapeUtils . escapeHtml4 ( request . getParameter ( "error_message" ) ) ) ; } model . put ( CasProtocolConstants . PARAMETER_SERVICE , request . getAttribute ( CasProtocolConstants . PARAMETER_SERVICE ) ) ; model . put ( "client" , StringEscapeUtils . escapeHtml4 ( request . getParameter ( "client_name" ) ) ) ; LOGGER . debug ( "Delegation request has failed. Details are [{}]" , model ) ; return Optional . of ( new ModelAndView ( "casPac4jStopWebflow" , model ) ) ; } return Optional . empty ( ) ; } | Determine if request has errors . |
18,371 | public EncryptedID encode ( final NameID samlObject , final SamlRegisteredService service , final SamlRegisteredServiceServiceProviderMetadataFacade adaptor ) { val encrypter = buildEncrypterForSamlObject ( samlObject , service , adaptor ) ; return encrypter . encrypt ( samlObject ) ; } | Encode encrypted id . |
18,372 | public EncryptedAttribute encode ( final Attribute samlObject , final SamlRegisteredService service , final SamlRegisteredServiceServiceProviderMetadataFacade adaptor ) { val encrypter = buildEncrypterForSamlObject ( samlObject , service , adaptor ) ; return encrypter . encrypt ( samlObject ) ; } | Encode encrypted attribute . |
18,373 | protected Encrypter buildEncrypterForSamlObject ( final Object samlObject , final SamlRegisteredService service , final SamlRegisteredServiceServiceProviderMetadataFacade adaptor ) { val className = samlObject . getClass ( ) . getName ( ) ; val entityId = adaptor . getEntityId ( ) ; LOGGER . debug ( "Attempting to encrypt [{}] for [{}]" , className , entityId ) ; val credential = getKeyEncryptionCredential ( entityId , adaptor , service ) ; LOGGER . info ( "Found encryption public key: [{}]" , EncodingUtils . encodeBase64 ( credential . getPublicKey ( ) . getEncoded ( ) ) ) ; val keyEncParams = getKeyEncryptionParameters ( samlObject , service , adaptor , credential ) ; LOGGER . debug ( "Key encryption algorithm for [{}] is [{}]" , keyEncParams . getRecipient ( ) , keyEncParams . getAlgorithm ( ) ) ; val dataEncParams = getDataEncryptionParameters ( samlObject , service , adaptor ) ; LOGGER . debug ( "Data encryption algorithm for [{}] is [{}]" , entityId , dataEncParams . getAlgorithm ( ) ) ; val encrypter = getEncrypter ( samlObject , service , adaptor , keyEncParams , dataEncParams ) ; LOGGER . debug ( "Attempting to encrypt [{}] for [{}] with key placement of [{}]" , className , entityId , encrypter . getKeyPlacement ( ) ) ; return encrypter ; } | Build encrypter for saml object encrypter . |
18,374 | protected Encrypter getEncrypter ( final Object samlObject , final SamlRegisteredService service , final SamlRegisteredServiceServiceProviderMetadataFacade adaptor , final KeyEncryptionParameters keyEncParams , final DataEncryptionParameters dataEncParams ) { val encrypter = new Encrypter ( dataEncParams , keyEncParams ) ; encrypter . setKeyPlacement ( Encrypter . KeyPlacement . PEER ) ; return encrypter ; } | Gets encrypter . |
18,375 | protected DataEncryptionParameters getDataEncryptionParameters ( final Object samlObject , final SamlRegisteredService service , final SamlRegisteredServiceServiceProviderMetadataFacade adaptor ) { val dataEncParams = new DataEncryptionParameters ( ) ; dataEncParams . setAlgorithm ( EncryptionConstants . ALGO_ID_BLOCKCIPHER_AES128 ) ; return dataEncParams ; } | Gets data encryption parameters . |
18,376 | protected KeyEncryptionParameters getKeyEncryptionParameters ( final Object samlObject , final SamlRegisteredService service , final SamlRegisteredServiceServiceProviderMetadataFacade adaptor , final Credential credential ) { val keyEncParams = new KeyEncryptionParameters ( ) ; keyEncParams . setRecipient ( adaptor . getEntityId ( ) ) ; keyEncParams . setEncryptionCredential ( credential ) ; keyEncParams . setAlgorithm ( EncryptionConstants . ALGO_ID_KEYTRANSPORT_RSAOAEP ) ; return keyEncParams ; } | Gets key encryption parameters . |
18,377 | protected Credential getKeyEncryptionCredential ( final String peerEntityId , final SamlRegisteredServiceServiceProviderMetadataFacade adaptor , final SamlRegisteredService service ) throws Exception { val config = DefaultSecurityConfigurationBootstrap . buildDefaultEncryptionConfiguration ( ) ; val overrideDataEncryptionAlgorithms = samlIdPProperties . getAlgs ( ) . getOverrideDataEncryptionAlgorithms ( ) ; val overrideKeyEncryptionAlgorithms = samlIdPProperties . getAlgs ( ) . getOverrideKeyEncryptionAlgorithms ( ) ; val overrideBlackListedEncryptionAlgorithms = samlIdPProperties . getAlgs ( ) . getOverrideBlackListedEncryptionAlgorithms ( ) ; val overrideWhiteListedAlgorithms = samlIdPProperties . getAlgs ( ) . getOverrideWhiteListedAlgorithms ( ) ; if ( overrideBlackListedEncryptionAlgorithms != null && ! overrideBlackListedEncryptionAlgorithms . isEmpty ( ) ) { config . setBlacklistedAlgorithms ( overrideBlackListedEncryptionAlgorithms ) ; } if ( overrideWhiteListedAlgorithms != null && ! overrideWhiteListedAlgorithms . isEmpty ( ) ) { config . setWhitelistedAlgorithms ( overrideWhiteListedAlgorithms ) ; } if ( overrideDataEncryptionAlgorithms != null && ! overrideDataEncryptionAlgorithms . isEmpty ( ) ) { config . setDataEncryptionAlgorithms ( overrideDataEncryptionAlgorithms ) ; } if ( overrideKeyEncryptionAlgorithms != null && ! overrideKeyEncryptionAlgorithms . isEmpty ( ) ) { config . setKeyTransportEncryptionAlgorithms ( overrideKeyEncryptionAlgorithms ) ; } LOGGER . debug ( "Encryption blacklisted algorithms: [{}]" , config . getBlacklistedAlgorithms ( ) ) ; LOGGER . debug ( "Encryption key algorithms: [{}]" , config . getKeyTransportEncryptionAlgorithms ( ) ) ; LOGGER . debug ( "Signature data algorithms: [{}]" , config . getDataEncryptionAlgorithms ( ) ) ; LOGGER . debug ( "Encryption whitelisted algorithms: [{}]" , config . getWhitelistedAlgorithms ( ) ) ; val kekCredentialResolver = new MetadataCredentialResolver ( ) ; val providers = new ArrayList < KeyInfoProvider > ( ) ; providers . add ( new RSAKeyValueProvider ( ) ) ; providers . add ( new DSAKeyValueProvider ( ) ) ; providers . add ( new InlineX509DataProvider ( ) ) ; providers . add ( new DEREncodedKeyValueProvider ( ) ) ; providers . add ( new KeyInfoReferenceProvider ( ) ) ; val keyInfoResolver = new BasicProviderKeyInfoCredentialResolver ( providers ) ; kekCredentialResolver . setKeyInfoCredentialResolver ( keyInfoResolver ) ; val roleDescriptorResolver = SamlIdPUtils . getRoleDescriptorResolver ( adaptor , samlIdPProperties . getMetadata ( ) . isRequireValidMetadata ( ) ) ; kekCredentialResolver . setRoleDescriptorResolver ( roleDescriptorResolver ) ; kekCredentialResolver . initialize ( ) ; val criteriaSet = new CriteriaSet ( ) ; criteriaSet . add ( new EncryptionConfigurationCriterion ( config ) ) ; criteriaSet . add ( new EntityIdCriterion ( peerEntityId ) ) ; criteriaSet . add ( new EntityRoleCriterion ( SPSSODescriptor . DEFAULT_ELEMENT_NAME ) ) ; criteriaSet . add ( new UsageCriterion ( UsageType . ENCRYPTION ) ) ; LOGGER . debug ( "Attempting to resolve the encryption key for entity id [{}]" , peerEntityId ) ; return kekCredentialResolver . resolveSingle ( criteriaSet ) ; } | Gets key encryption credential . |
18,378 | @ GetMapping ( "/openid/*" ) protected ModelAndView handleRequestInternal ( final HttpServletRequest request , final HttpServletResponse response ) { return new ModelAndView ( "openIdProviderView" , CollectionUtils . wrap ( "openid_server" , casProperties . getServer ( ) . getPrefix ( ) ) ) ; } | Handle request internal model and view . |
18,379 | private static String normalizePath ( final Service service ) { var path = service . getId ( ) ; path = StringUtils . substringBefore ( path , "?" ) ; path = StringUtils . substringBefore ( path , ";" ) ; path = StringUtils . substringBefore ( path , "#" ) ; return path ; } | Normalize the path of a service by removing the query string and everything after a semi - colon . |
18,380 | protected void trackServiceSession ( final String id , final Service service , final boolean onlyTrackMostRecentSession ) { update ( ) ; service . setPrincipal ( getRoot ( ) . getAuthentication ( ) . getPrincipal ( ) . getId ( ) ) ; if ( onlyTrackMostRecentSession ) { val path = normalizePath ( service ) ; val existingServices = this . services . values ( ) ; existingServices . stream ( ) . filter ( existingService -> path . equals ( normalizePath ( existingService ) ) ) . findFirst ( ) . ifPresent ( existingServices :: remove ) ; } this . services . put ( id , service ) ; } | Update service and track session . |
18,381 | public GeoLocationResponse addAddress ( final String address ) { if ( StringUtils . isNotBlank ( address ) ) { this . addresses . add ( address ) ; } return this ; } | Add address . |
18,382 | protected String getCurrentTheme ( ) { val request = WebUtils . getHttpServletRequestFromExternalWebflowContext ( ) ; if ( request != null ) { val session = request . getSession ( false ) ; val paramName = casProperties . getTheme ( ) . getParamName ( ) ; if ( session != null ) { return ( String ) session . getAttribute ( paramName ) ; } return ( String ) request . getAttribute ( paramName ) ; } return null ; } | Gets current theme . |
18,383 | public int deleteAll ( ) { val count = new AtomicInteger ( ) ; val metadata = this . ticketCatalog . findAll ( ) ; metadata . forEach ( r -> { val scan = new ScanRequest ( r . getProperties ( ) . getStorageName ( ) ) ; LOGGER . debug ( "Submitting scan request [{}] to table [{}]" , scan , r . getProperties ( ) . getStorageName ( ) ) ; count . addAndGet ( this . amazonDynamoDBClient . scan ( scan ) . getCount ( ) ) ; } ) ; createTicketTables ( true ) ; return count . get ( ) ; } | Delete all . |
18,384 | public Ticket get ( final String ticketId , final String encodedTicketId ) { val metadata = this . ticketCatalog . find ( ticketId ) ; if ( metadata != null ) { val keys = new HashMap < String , AttributeValue > ( ) ; keys . put ( ColumnNames . ID . getColumnName ( ) , new AttributeValue ( encodedTicketId ) ) ; val request = new GetItemRequest ( ) . withKey ( keys ) . withTableName ( metadata . getProperties ( ) . getStorageName ( ) ) ; LOGGER . debug ( "Submitting request [{}] to get ticket item [{}]" , request , ticketId ) ; val returnItem = amazonDynamoDBClient . getItem ( request ) . getItem ( ) ; if ( returnItem != null ) { val ticket = deserializeTicket ( returnItem ) ; LOGGER . debug ( "Located ticket [{}]" , ticket ) ; if ( ticket == null || ticket . isExpired ( ) ) { LOGGER . warn ( "The expiration policy for ticket id [{}] has expired the ticket" , ticketId ) ; return null ; } return ticket ; } } else { LOGGER . warn ( "No ticket definition could be found in the catalog to match [{}]" , ticketId ) ; } return null ; } | Get ticket . |
18,385 | public void put ( final Ticket ticket , final Ticket encodedTicket ) { val metadata = this . ticketCatalog . find ( ticket ) ; val values = buildTableAttributeValuesMapFromTicket ( ticket , encodedTicket ) ; LOGGER . debug ( "Adding ticket id [{}] with attribute values [{}]" , encodedTicket . getId ( ) , values ) ; val putItemRequest = new PutItemRequest ( metadata . getProperties ( ) . getStorageName ( ) , values ) ; LOGGER . debug ( "Submitting put request [{}] for ticket id [{}]" , putItemRequest , encodedTicket . getId ( ) ) ; val putItemResult = amazonDynamoDBClient . putItem ( putItemRequest ) ; LOGGER . debug ( "Ticket added with result [{}]" , putItemResult ) ; getAll ( ) ; } | Put ticket . |
18,386 | public void createTicketTables ( final boolean deleteTables ) { val metadata = this . ticketCatalog . findAll ( ) ; metadata . forEach ( Unchecked . consumer ( r -> { val request = new CreateTableRequest ( ) . withAttributeDefinitions ( new AttributeDefinition ( ColumnNames . ID . getColumnName ( ) , ScalarAttributeType . S ) ) . withKeySchema ( new KeySchemaElement ( ColumnNames . ID . getColumnName ( ) , KeyType . HASH ) ) . withProvisionedThroughput ( new ProvisionedThroughput ( dynamoDbProperties . getReadCapacity ( ) , dynamoDbProperties . getWriteCapacity ( ) ) ) . withTableName ( r . getProperties ( ) . getStorageName ( ) ) ; if ( deleteTables ) { val delete = new DeleteTableRequest ( r . getProperties ( ) . getStorageName ( ) ) ; LOGGER . debug ( "Sending delete request [{}] to remove table if necessary" , delete ) ; TableUtils . deleteTableIfExists ( amazonDynamoDBClient , delete ) ; } LOGGER . debug ( "Sending delete request [{}] to create table" , request ) ; TableUtils . createTableIfNotExists ( amazonDynamoDBClient , request ) ; LOGGER . debug ( "Waiting until table [{}] becomes active..." , request . getTableName ( ) ) ; TableUtils . waitUntilActive ( amazonDynamoDBClient , request . getTableName ( ) ) ; val describeTableRequest = new DescribeTableRequest ( ) . withTableName ( request . getTableName ( ) ) ; LOGGER . debug ( "Sending request [{}] to obtain table description..." , describeTableRequest ) ; val tableDescription = amazonDynamoDBClient . describeTable ( describeTableRequest ) . getTable ( ) ; LOGGER . debug ( "Located newly created table with description: [{}]" , tableDescription ) ; } ) ) ; } | Create ticket tables . |
18,387 | public Map < String , AttributeValue > buildTableAttributeValuesMapFromTicket ( final Ticket ticket , final Ticket encTicket ) { val values = new HashMap < String , AttributeValue > ( ) ; values . put ( ColumnNames . ID . getColumnName ( ) , new AttributeValue ( encTicket . getId ( ) ) ) ; values . put ( ColumnNames . PREFIX . getColumnName ( ) , new AttributeValue ( ticket . getPrefix ( ) ) ) ; values . put ( ColumnNames . CREATION_TIME . getColumnName ( ) , new AttributeValue ( ticket . getCreationTime ( ) . toString ( ) ) ) ; values . put ( ColumnNames . COUNT_OF_USES . getColumnName ( ) , new AttributeValue ( ) . withN ( Integer . toString ( ticket . getCountOfUses ( ) ) ) ) ; values . put ( ColumnNames . TIME_TO_LIVE . getColumnName ( ) , new AttributeValue ( ) . withN ( Long . toString ( ticket . getExpirationPolicy ( ) . getTimeToLive ( ) ) ) ) ; values . put ( ColumnNames . TIME_TO_IDLE . getColumnName ( ) , new AttributeValue ( ) . withN ( Long . toString ( ticket . getExpirationPolicy ( ) . getTimeToIdle ( ) ) ) ) ; values . put ( ColumnNames . ENCODED . getColumnName ( ) , new AttributeValue ( ) . withB ( ByteBuffer . wrap ( SerializationUtils . serialize ( encTicket ) ) ) ) ; LOGGER . debug ( "Created attribute values [{}] based on provided ticket [{}]" , values , encTicket . getId ( ) ) ; return values ; } | Build table attribute values from ticket map . |
18,388 | public static DefaultAuthenticationTransaction of ( final Service service , final Credential ... credentials ) { val creds = sanitizeCredentials ( credentials ) ; return new DefaultAuthenticationTransaction ( service , creds ) ; } | Wrap credentials into an authentication transaction as a factory method and return the final result . |
18,389 | private static Set < Credential > sanitizeCredentials ( final Credential [ ] credentials ) { if ( credentials != null && credentials . length > 0 ) { return Arrays . stream ( credentials ) . filter ( Objects :: nonNull ) . collect ( Collectors . toCollection ( LinkedHashSet :: new ) ) ; } return new HashSet < > ( 0 ) ; } | Sanitize credentials set . It s important to keep the order of the credentials in the final set as they were presented . |
18,390 | public void parseCompilationUnit ( final Set < ConfigurationMetadataProperty > collectedProps , final Set < ConfigurationMetadataProperty > collectedGroups , final ConfigurationMetadataProperty p , final String typePath , final String typeName , final boolean indexNameWithBrackets ) { try ( val is = Files . newInputStream ( Paths . get ( typePath ) ) ) { val cu = StaticJavaParser . parse ( is ) ; new ConfigurationMetadataFieldVisitor ( collectedProps , collectedGroups , indexNameWithBrackets , typeName , sourcePath ) . visit ( cu , p ) ; if ( ! cu . getTypes ( ) . isEmpty ( ) ) { val decl = ClassOrInterfaceDeclaration . class . cast ( cu . getType ( 0 ) ) ; for ( var i = 0 ; i < decl . getExtendedTypes ( ) . size ( ) ; i ++ ) { val parentType = decl . getExtendedTypes ( ) . get ( i ) ; val instance = ConfigurationMetadataClassSourceLocator . getInstance ( ) ; val parentClazz = instance . locatePropertiesClassForType ( parentType ) ; val parentTypePath = ConfigurationMetadataClassSourceLocator . buildTypeSourcePath ( this . sourcePath , parentClazz . getName ( ) ) ; parseCompilationUnit ( collectedProps , collectedGroups , p , parentTypePath , parentClazz . getName ( ) , indexNameWithBrackets ) ; } } } } | Parse compilation unit . |
18,391 | protected String determineThemeNameToChoose ( final HttpServletRequest request , final Service service , final RegisteredService rService ) { HttpResponse response = null ; try { LOGGER . debug ( "Service [{}] is configured to use a custom theme [{}]" , rService , rService . getTheme ( ) ) ; val resource = ResourceUtils . getRawResourceFrom ( rService . getTheme ( ) ) ; if ( resource instanceof FileSystemResource && resource . exists ( ) ) { LOGGER . debug ( "Executing groovy script to determine theme for [{}]" , service . getId ( ) ) ; val result = ScriptingUtils . executeGroovyScript ( resource , new Object [ ] { service , rService , request . getQueryString ( ) , HttpRequestUtils . getRequestHeaders ( request ) , LOGGER } , String . class , true ) ; return StringUtils . defaultIfBlank ( result , getDefaultThemeName ( ) ) ; } if ( resource instanceof UrlResource ) { val url = resource . getURL ( ) . toExternalForm ( ) ; LOGGER . debug ( "Executing URL [{}] to determine theme for [{}]" , url , service . getId ( ) ) ; response = HttpUtils . executeGet ( url , CollectionUtils . wrap ( "service" , service . getId ( ) ) ) ; if ( response != null && response . getStatusLine ( ) . getStatusCode ( ) == HttpStatus . SC_OK ) { val result = IOUtils . toString ( response . getEntity ( ) . getContent ( ) , StandardCharsets . UTF_8 ) ; return StringUtils . defaultIfBlank ( result , getDefaultThemeName ( ) ) ; } } val messageSource = new CasThemeResourceBundleMessageSource ( ) ; messageSource . setBasename ( rService . getTheme ( ) ) ; if ( messageSource . doGetBundle ( rService . getTheme ( ) , request . getLocale ( ) ) != null ) { LOGGER . trace ( "Found custom theme [{}] for service [{}]" , rService . getTheme ( ) , rService ) ; return rService . getTheme ( ) ; } LOGGER . warn ( "Custom theme [{}] for service [{}] cannot be located. Falling back to default theme..." , rService . getTheme ( ) , rService ) ; } catch ( final Exception e ) { LOGGER . error ( e . getMessage ( ) , e ) ; } finally { HttpUtils . close ( response ) ; } return getDefaultThemeName ( ) ; } | Determine theme name to choose . |
18,392 | protected String callRestEndpointForMultifactor ( final Principal principal , final Service resolvedService ) { val restTemplate = new RestTemplate ( ) ; val restEndpoint = casProperties . getAuthn ( ) . getMfa ( ) . getRestEndpoint ( ) ; val entity = new RestEndpointEntity ( principal . getId ( ) , resolvedService . getId ( ) ) ; val responseEntity = restTemplate . postForEntity ( restEndpoint , entity , String . class ) ; if ( responseEntity . getStatusCode ( ) == HttpStatus . OK ) { return responseEntity . getBody ( ) ; } return null ; } | Call rest endpoint for multifactor . |
18,393 | protected boolean isAccessTokenExpired ( final TicketState ticketState ) { val currentSystemTime = ZonedDateTime . now ( ZoneOffset . UTC ) ; val creationTime = ticketState . getCreationTime ( ) ; var expirationTime = creationTime . plus ( this . maxTimeToLiveInSeconds , ChronoUnit . SECONDS ) ; if ( currentSystemTime . isAfter ( expirationTime ) ) { LOGGER . debug ( "Access token is expired because the time since creation is greater than maxTimeToLiveInSeconds" ) ; return true ; } val expirationTimeToKill = ticketState . getLastTimeUsed ( ) . plus ( this . timeToKillInSeconds , ChronoUnit . SECONDS ) ; if ( currentSystemTime . isAfter ( expirationTimeToKill ) ) { LOGGER . debug ( "Access token is expired because the time since last use is greater than timeToKillInSeconds" ) ; return true ; } return false ; } | Is access token expired ? . |
18,394 | public static Set < String > getOidcPromptFromAuthorizationRequest ( final String url ) { return new URIBuilder ( url ) . getQueryParams ( ) . stream ( ) . filter ( p -> OidcConstants . PROMPT . equals ( p . getName ( ) ) ) . map ( param -> param . getValue ( ) . split ( " " ) ) . flatMap ( Arrays :: stream ) . collect ( Collectors . toSet ( ) ) ; } | Gets oidc prompt from authorization request . |
18,395 | public static Optional < Long > getOidcMaxAgeFromAuthorizationRequest ( final WebContext context ) { val builderContext = new URIBuilder ( context . getFullRequestURL ( ) ) ; val parameter = builderContext . getQueryParams ( ) . stream ( ) . filter ( p -> OidcConstants . MAX_AGE . equals ( p . getName ( ) ) ) . findFirst ( ) ; if ( parameter . isPresent ( ) ) { val maxAge = NumberUtils . toLong ( parameter . get ( ) . getValue ( ) , - 1 ) ; return Optional . of ( maxAge ) ; } return Optional . empty ( ) ; } | Gets oidc max age from authorization request . |
18,396 | public static Optional < CommonProfile > isAuthenticationProfileAvailable ( final J2EContext context ) { val manager = new ProfileManager < > ( context , context . getSessionStore ( ) ) ; return manager . get ( true ) ; } | Is authentication profile available? . |
18,397 | public Optional < Authentication > isCasAuthenticationAvailable ( final WebContext context ) { val j2EContext = ( J2EContext ) context ; if ( j2EContext != null ) { val tgtId = ticketGrantingTicketCookieGenerator . retrieveCookieValue ( j2EContext . getRequest ( ) ) ; if ( StringUtils . isNotBlank ( tgtId ) ) { val authentication = ticketRegistrySupport . getAuthenticationFrom ( tgtId ) ; if ( authentication != null ) { return Optional . of ( authentication ) ; } } } return Optional . empty ( ) ; } | Is cas authentication available? |
18,398 | public static boolean isCasAuthenticationOldForMaxAgeAuthorizationRequest ( final WebContext context , final ZonedDateTime authenticationDate ) { val maxAge = getOidcMaxAgeFromAuthorizationRequest ( context ) ; if ( maxAge . isPresent ( ) && maxAge . get ( ) > 0 ) { val now = ZonedDateTime . now ( ZoneOffset . UTC ) . toEpochSecond ( ) ; val authTime = authenticationDate . toEpochSecond ( ) ; val diffInSeconds = now - authTime ; if ( diffInSeconds > maxAge . get ( ) ) { LOGGER . info ( "Authentication is too old: [{}] and was created [{}] seconds ago." , authTime , diffInSeconds ) ; return true ; } } return false ; } | Is cas authentication old for max age authorization request boolean . |
18,399 | public boolean isCasAuthenticationOldForMaxAgeAuthorizationRequest ( final WebContext context ) { return isCasAuthenticationAvailable ( context ) . filter ( a -> isCasAuthenticationOldForMaxAgeAuthorizationRequest ( context , a ) ) . isPresent ( ) ; } | Is cas authentication available and old for max age authorization request? |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.