idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
17,800 | public static Key generateJsonWebKey ( final String secret ) { val keys = new HashMap < String , Object > ( 2 ) ; keys . put ( "kty" , "oct" ) ; keys . put ( EncodingUtils . JSON_WEB_KEY , secret ) ; val jwk = JsonWebKey . Factory . newJwk ( keys ) ; return jwk . getKey ( ) ; } | Prepare json web token key . |
17,801 | public static byte [ ] signJws ( final Key key , final byte [ ] value , final String algHeaderValue ) { val base64 = EncodingUtils . encodeBase64 ( value ) ; val jws = new JsonWebSignature ( ) ; jws . setEncodedPayload ( base64 ) ; jws . setAlgorithmHeaderValue ( algHeaderValue ) ; jws . setKey ( key ) ; jws . setHeader ( "typ" , "JWT" ) ; return jws . getCompactSerialization ( ) . getBytes ( StandardCharsets . UTF_8 ) ; } | Sign jws . |
17,802 | public static String encryptValueAsJwtDirectAes128Sha256 ( final Key key , final Serializable value ) { return encryptValueAsJwt ( key , value , KeyManagementAlgorithmIdentifiers . DIRECT , CipherExecutor . DEFAULT_CONTENT_ENCRYPTION_ALGORITHM ) ; } | Encrypt value as jwt with direct algorithm and encryption content alg aes - 128 - sha - 256 . |
17,803 | public static String encryptValueAsJwtRsaOeap256Aes256Sha512 ( final Key key , final Serializable value ) { return encryptValueAsJwt ( key , value , KeyManagementAlgorithmIdentifiers . RSA_OAEP_256 , CipherExecutor . DEFAULT_CONTENT_ENCRYPTION_ALGORITHM ) ; } | Encrypt value as jwt rsa oeap 256 aes 256 sha 512 string . |
17,804 | public static String encryptValueAsJwt ( final Key secretKeyEncryptionKey , final Serializable value , final String algorithmHeaderValue , final String contentEncryptionAlgorithmIdentifier ) { try { val jwe = new JsonWebEncryption ( ) ; jwe . setPayload ( value . toString ( ) ) ; jwe . enableDefaultCompression ( ) ; jwe . setAlgorithmHeaderValue ( algorithmHeaderValue ) ; jwe . setEncryptionMethodHeaderParameter ( contentEncryptionAlgorithmIdentifier ) ; jwe . setKey ( secretKeyEncryptionKey ) ; jwe . setHeader ( "typ" , "JWT" ) ; LOGGER . trace ( "Encrypting via [{}]" , contentEncryptionAlgorithmIdentifier ) ; return jwe . getCompactSerialization ( ) ; } catch ( final JoseException e ) { throw new IllegalArgumentException ( "Is JCE Unlimited Strength Jurisdiction Policy installed? " + e . getMessage ( ) , e ) ; } } | Encrypt the value based on the seed array whose length was given during afterPropertiesSet and the key and content encryption ids . |
17,805 | public static String decryptJwtValue ( final Key secretKeyEncryptionKey , final String value ) { val jwe = new JsonWebEncryption ( ) ; jwe . setKey ( secretKeyEncryptionKey ) ; jwe . setCompactSerialization ( value ) ; LOGGER . trace ( "Decrypting value..." ) ; try { return jwe . getPayload ( ) ; } catch ( final JoseException e ) { if ( LOGGER . isTraceEnabled ( ) ) { throw new DecryptionException ( e ) ; } throw new DecryptionException ( ) ; } } | Decrypt value based on the key created . |
17,806 | public static boolean isJceInstalled ( ) { try { val maxKeyLen = Cipher . getMaxAllowedKeyLength ( "AES" ) ; return maxKeyLen == Integer . MAX_VALUE ; } catch ( final NoSuchAlgorithmException e ) { return false ; } } | Is jce installed ? |
17,807 | protected boolean isRequestAskingForServiceTicket ( final RequestContext context ) { val ticketGrantingTicketId = WebUtils . getTicketGrantingTicketId ( context ) ; LOGGER . debug ( "Located ticket-granting ticket [{}] from the request context" , ticketGrantingTicketId ) ; val service = WebUtils . getService ( context ) ; LOGGER . debug ( "Located service [{}] from the request context" , service ) ; val renewParam = getWebflowEventResolutionConfigurationContext ( ) . getCasProperties ( ) . getSso ( ) . isRenewAuthnEnabled ( ) ? context . getRequestParameters ( ) . get ( CasProtocolConstants . PARAMETER_RENEW ) : StringUtils . EMPTY ; LOGGER . debug ( "Provided value for [{}] request parameter is [{}]" , CasProtocolConstants . PARAMETER_RENEW , renewParam ) ; if ( service != null && StringUtils . isNotBlank ( ticketGrantingTicketId ) ) { val authn = getWebflowEventResolutionConfigurationContext ( ) . getTicketRegistrySupport ( ) . getAuthenticationFrom ( ticketGrantingTicketId ) ; if ( StringUtils . isNotBlank ( renewParam ) ) { LOGGER . debug ( "Request identifies itself as one asking for service tickets. Checking for authentication context validity..." ) ; val validAuthn = authn != null ; if ( validAuthn ) { LOGGER . debug ( "Existing authentication context linked to ticket-granting ticket [{}] is valid. " + "CAS should begin to issue service tickets for [{}] once credentials are renewed" , ticketGrantingTicketId , service ) ; return true ; } LOGGER . debug ( "Existing authentication context linked to ticket-granting ticket [{}] is NOT valid. " + "CAS will not issue service tickets for [{}] just yet without renewing the authentication context" , ticketGrantingTicketId , service ) ; return false ; } } LOGGER . debug ( "Request is not eligible to be issued service tickets just yet" ) ; return false ; } | Is request asking for service ticket? |
17,808 | protected Event grantServiceTicket ( final RequestContext context ) { val ticketGrantingTicketId = WebUtils . getTicketGrantingTicketId ( context ) ; val credential = getCredentialFromContext ( context ) ; try { val service = WebUtils . getService ( context ) ; val authn = getWebflowEventResolutionConfigurationContext ( ) . getTicketRegistrySupport ( ) . getAuthenticationFrom ( ticketGrantingTicketId ) ; val registeredService = getWebflowEventResolutionConfigurationContext ( ) . getServicesManager ( ) . findServiceBy ( service ) ; if ( authn != null && registeredService != null ) { LOGGER . debug ( "Enforcing access strategy policies for registered service [{}] and principal [{}]" , registeredService , authn . getPrincipal ( ) ) ; val audit = AuditableContext . builder ( ) . service ( service ) . authentication ( authn ) . registeredService ( registeredService ) . retrievePrincipalAttributesFromReleasePolicy ( Boolean . TRUE ) . build ( ) ; val accessResult = getWebflowEventResolutionConfigurationContext ( ) . getRegisteredServiceAccessStrategyEnforcer ( ) . execute ( audit ) ; accessResult . throwExceptionIfNeeded ( ) ; } val authenticationResult = getWebflowEventResolutionConfigurationContext ( ) . getAuthenticationSystemSupport ( ) . handleAndFinalizeSingleAuthenticationTransaction ( service , credential ) ; val serviceTicketId = getWebflowEventResolutionConfigurationContext ( ) . getCentralAuthenticationService ( ) . grantServiceTicket ( ticketGrantingTicketId , service , authenticationResult ) ; WebUtils . putServiceTicketInRequestScope ( context , serviceTicketId ) ; WebUtils . putWarnCookieIfRequestParameterPresent ( getWebflowEventResolutionConfigurationContext ( ) . getWarnCookieGenerator ( ) , context ) ; return newEvent ( CasWebflowConstants . TRANSITION_ID_WARN ) ; } catch ( final AuthenticationException | AbstractTicketException e ) { return newEvent ( CasWebflowConstants . TRANSITION_ID_AUTHENTICATION_FAILURE , e ) ; } } | Grant service ticket for the given credential based on the service and tgt that are found in the request context . |
17,809 | public boolean supports ( final Credential credentials ) { return credentials != null && WsFederationCredential . class . isAssignableFrom ( credentials . getClass ( ) ) ; } | Determines if this handler can support the credentials provided . |
17,810 | @ ShellMethod ( key = "jasypt-list-algorithms" , value = "List alogrithms you can use with Jasypt for property encryption" ) public void listAlgorithms ( @ ShellOption ( value = { "includeBC" } , help = "Include Bouncy Castle provider" ) final boolean includeBC ) { if ( includeBC ) { if ( Security . getProvider ( BouncyCastleProvider . PROVIDER_NAME ) == null ) { Security . addProvider ( new BouncyCastleProvider ( ) ) ; } } else { Security . removeProvider ( BouncyCastleProvider . PROVIDER_NAME ) ; } val providers = Security . getProviders ( ) ; LOGGER . info ( "Loaded providers: " ) ; for ( val provider : providers ) { LOGGER . info ( "Provider: [{}] [{}]" , provider . getName ( ) , provider . getClass ( ) . getName ( ) ) ; } val pbeAlgos = AlgorithmRegistry . getAllPBEAlgorithms ( ) ; LOGGER . info ( "==== JASYPT Password Based Encryption Algorithms ====\n" ) ; for ( val pbeAlgo : pbeAlgos ) { LOGGER . info ( pbeAlgo . toString ( ) ) ; } } | List algorithms you can use Jasypt . |
17,811 | @ GetMapping ( "/sp/metadata" ) public ResponseEntity < String > getFirstServiceProviderMetadata ( ) { val saml2Client = builtClients . findClient ( SAML2Client . class ) ; if ( saml2Client != null ) { return getSaml2ClientServiceProviderMetadataResponseEntity ( saml2Client ) ; } return getNotAcceptableResponseEntity ( ) ; } | Gets first service provider metadata . |
17,812 | @ GetMapping ( "/sp/idp/metadata" ) public ResponseEntity < String > getFirstIdentityProviderMetadata ( ) { val saml2Client = builtClients . findClient ( SAML2Client . class ) ; if ( saml2Client != null ) { return getSaml2ClientIdentityProviderMetadataResponseEntity ( saml2Client ) ; } return getNotAcceptableResponseEntity ( ) ; } | Gets first idp metadata . |
17,813 | @ GetMapping ( "/sp/{client}/metadata" ) public ResponseEntity < String > getServiceProviderMetadataByName ( @ PathVariable ( "client" ) final String client ) { val saml2Client = ( SAML2Client ) builtClients . findClient ( client ) ; if ( saml2Client != null ) { return getSaml2ClientServiceProviderMetadataResponseEntity ( saml2Client ) ; } return getNotAcceptableResponseEntity ( ) ; } | Gets service provider metadata by name . |
17,814 | @ GetMapping ( "/sp/{client}/idp/metadata" ) public ResponseEntity < String > getIdentityProviderMetadataByName ( @ PathVariable ( "client" ) final String client ) { val saml2Client = ( SAML2Client ) builtClients . findClient ( client ) ; if ( saml2Client != null ) { return getSaml2ClientIdentityProviderMetadataResponseEntity ( saml2Client ) ; } return getNotAcceptableResponseEntity ( ) ; } | Gets idp metadata by name . |
17,815 | @ ShellMethod ( key = "jasypt-list-providers" , value = "List encryption providers with PBE Ciphers you can use with Jasypt" ) public void listAlgorithms ( @ ShellOption ( value = { "includeBC" } , help = "Include Bouncy Castle provider" ) final boolean includeBC ) { if ( includeBC ) { if ( Security . getProvider ( BouncyCastleProvider . PROVIDER_NAME ) == null ) { Security . addProvider ( new BouncyCastleProvider ( ) ) ; } } else { Security . removeProvider ( BouncyCastleProvider . PROVIDER_NAME ) ; } val providers = Security . getProviders ( ) ; for ( val provider : providers ) { val services = provider . getServices ( ) ; val algorithms = services . stream ( ) . filter ( service -> "Cipher" . equals ( service . getType ( ) ) && service . getAlgorithm ( ) . contains ( "PBE" ) ) . map ( Provider . Service :: getAlgorithm ) . collect ( Collectors . toList ( ) ) ; if ( ! algorithms . isEmpty ( ) ) { LOGGER . info ( "Provider: Name: [{}] Class: [{}]" , provider . getName ( ) , provider . getClass ( ) . getName ( ) ) ; for ( val algorithm : algorithms ) { LOGGER . info ( " - Algorithm: [{}]" , algorithm ) ; } } } } | List providers you can use Jasypt . |
17,816 | public static String generateGeography ( ) { val clientInfo = ClientInfoHolder . getClientInfo ( ) ; return clientInfo . getClientIpAddress ( ) . concat ( "@" ) . concat ( WebUtils . getHttpServletRequestUserAgentFromRequestContext ( ) ) ; } | Generate geography . |
17,817 | public static void trackTrustedMultifactorAuthenticationAttribute ( final Authentication authn , final String attributeName ) { val newAuthn = DefaultAuthenticationBuilder . newInstance ( authn ) . addAttribute ( attributeName , Boolean . TRUE ) . build ( ) ; LOGGER . debug ( "Updated authentication session to remember trusted multifactor record via [{}]" , attributeName ) ; authn . update ( newAuthn ) ; } | Track trusted multifactor authentication attribute . |
17,818 | public static void setMultifactorAuthenticationTrustedInScope ( final RequestContext requestContext ) { val flashScope = requestContext . getFlashScope ( ) ; flashScope . put ( AbstractMultifactorTrustedDeviceWebflowConfigurer . MFA_TRUSTED_AUTHN_SCOPE_ATTR , Boolean . TRUE ) ; } | Sets multifactor authentication trusted in scope . |
17,819 | public static MultifactorAuthenticationTrustRecord newInstance ( final String principal , final String geography , final String fingerprint ) { val r = new MultifactorAuthenticationTrustRecord ( ) ; r . setRecordDate ( LocalDateTime . now ( ) . truncatedTo ( ChronoUnit . SECONDS ) ) ; r . setPrincipal ( principal ) ; r . setDeviceFingerprint ( fingerprint ) ; r . setName ( principal . concat ( "-" ) . concat ( LocalDate . now ( ) . toString ( ) ) . concat ( "-" ) . concat ( geography ) ) ; return r ; } | New instance of authentication trust record . |
17,820 | public MongoTemplate buildMongoTemplate ( final BaseMongoDbProperties mongo ) { val mongoDbFactory = mongoDbFactory ( buildMongoDbClient ( mongo ) , mongo ) ; return new MongoTemplate ( mongoDbFactory , mappingMongoConverter ( mongoDbFactory ) ) ; } | Build mongo template . |
17,821 | public void createCollection ( final MongoOperations mongoTemplate , final String collectionName , final boolean dropCollection ) { if ( dropCollection ) { LOGGER . trace ( "Dropping database collection: [{}]" , collectionName ) ; mongoTemplate . dropCollection ( collectionName ) ; } if ( ! mongoTemplate . collectionExists ( collectionName ) ) { LOGGER . trace ( "Creating database collection: [{}]" , collectionName ) ; mongoTemplate . createCollection ( collectionName ) ; } } | Create collection . |
17,822 | public static MongoClient buildMongoDbClient ( final BaseMongoDbProperties mongo ) { if ( StringUtils . isNotBlank ( mongo . getClientUri ( ) ) ) { LOGGER . debug ( "Using MongoDb client URI [{}] to connect to MongoDb instance" , mongo . getClientUri ( ) ) ; return buildMongoDbClient ( mongo . getClientUri ( ) , buildMongoDbClientOptions ( mongo ) ) ; } val serverAddresses = mongo . getHost ( ) . split ( "," ) ; if ( serverAddresses . length == 0 ) { throw new BeanCreationException ( "Unable to build a MongoDb client without any hosts/servers defined" ) ; } List < ServerAddress > servers = new ArrayList < > ( ) ; if ( serverAddresses . length > 1 ) { LOGGER . debug ( "Multiple MongoDb server addresses are defined. Ignoring port [{}], " + "assuming ports are defined as part of the address" , mongo . getPort ( ) ) ; servers = Arrays . stream ( serverAddresses ) . filter ( StringUtils :: isNotBlank ) . map ( ServerAddress :: new ) . collect ( Collectors . toList ( ) ) ; } else { val port = mongo . getPort ( ) > 0 ? mongo . getPort ( ) : DEFAULT_PORT ; LOGGER . debug ( "Found single MongoDb server address [{}] using port [{}]" , mongo . getHost ( ) , port ) ; val addr = new ServerAddress ( mongo . getHost ( ) , port ) ; servers . add ( addr ) ; } val credential = buildMongoCredential ( mongo ) ; return new MongoClient ( servers , CollectionUtils . wrap ( credential ) , buildMongoDbClientOptions ( mongo ) ) ; } | Build mongo db client . |
17,823 | public Map < String , String > configureAttributeNameFormats ( ) { if ( this . attributeNameFormats . isEmpty ( ) ) { return new HashMap < > ( 0 ) ; } val nameFormats = new HashMap < String , String > ( ) ; this . attributeNameFormats . forEach ( value -> Arrays . stream ( value . split ( "," ) ) . forEach ( format -> { val values = Splitter . on ( "->" ) . splitToList ( format ) ; if ( values . size ( ) == 2 ) { nameFormats . put ( values . get ( 0 ) , values . get ( 1 ) ) ; } } ) ) ; return nameFormats ; } | Configure attribute name formats and build a map . |
17,824 | protected Connection createConnection ( ) throws LdapException { LOGGER . debug ( "Establishing a connection..." ) ; val connection = this . connectionFactory . getConnection ( ) ; connection . open ( ) ; return connection ; } | Create and open a connection to ldap via the given config and provider . |
17,825 | protected boolean executeSearchForSpnegoAttribute ( final String remoteIp ) { val remoteHostName = getRemoteHostName ( remoteIp ) ; LOGGER . debug ( "Resolved remote hostname [{}] based on ip [{}]" , remoteHostName , remoteIp ) ; try ( val connection = createConnection ( ) ) { val searchOperation = new SearchOperation ( connection ) ; this . searchRequest . getSearchFilter ( ) . setParameter ( "host" , remoteHostName ) ; LOGGER . debug ( "Using search filter [{}] on baseDn [{}]" , this . searchRequest . getSearchFilter ( ) . format ( ) , this . searchRequest . getBaseDn ( ) ) ; val searchResult = searchOperation . execute ( this . searchRequest ) ; if ( searchResult . getResultCode ( ) == ResultCode . SUCCESS ) { return processSpnegoAttribute ( searchResult ) ; } throw new IllegalArgumentException ( "Failed to establish a connection ldap. " + searchResult . getMessage ( ) ) ; } } | Searches the ldap instance for the attribute value . |
17,826 | protected boolean processSpnegoAttribute ( final Response < SearchResult > searchResult ) { val result = searchResult . getResult ( ) ; if ( result == null || result . getEntries ( ) . isEmpty ( ) ) { LOGGER . debug ( "Spnego attribute is not found in the search results" ) ; return false ; } val entry = result . getEntry ( ) ; val attribute = entry . getAttribute ( this . spnegoAttributeName ) ; LOGGER . debug ( "Spnego attribute [{}] found as [{}] for [{}]" , attribute . getName ( ) , attribute . getStringValue ( ) , entry . getDn ( ) ) ; return verifySpnegoAttributeValue ( attribute ) ; } | Verify spnego attribute value . |
17,827 | public Map < String , List < Object > > getCachedAttributesFor ( final RegisteredService registeredService , final CachingPrincipalAttributesRepository repository , final Principal principal ) { val cache = getRegisteredServiceCacheInstance ( registeredService , repository ) ; return cache . get ( principal . getId ( ) , s -> { LOGGER . debug ( "No cached attributes could be found for [{}]" , principal . getId ( ) ) ; return new TreeMap < > ( String . CASE_INSENSITIVE_ORDER ) ; } ) ; } | Gets cached attributes . Locate the cache for the service first . |
17,828 | public void putCachedAttributesFor ( final RegisteredService registeredService , final CachingPrincipalAttributesRepository repository , final String id , final Map < String , List < Object > > attributes ) { val cache = getRegisteredServiceCacheInstance ( registeredService , repository ) ; cache . put ( id , attributes ) ; } | Put cached attributes . |
17,829 | private Cache < String , Map < String , List < Object > > > getRegisteredServiceCacheInstance ( final RegisteredService registeredService , final CachingPrincipalAttributesRepository repository ) { val key = buildRegisteredServiceCacheKey ( registeredService ) ; if ( registeredServicesCache . containsKey ( key ) ) { return registeredServicesCache . get ( key ) ; } val cache = initializeCache ( repository ) ; registeredServicesCache . put ( key , cache ) ; return cache ; } | Gets registered service cache instance . |
17,830 | private static Cache < String , Map < String , List < Object > > > initializeCache ( final CachingPrincipalAttributesRepository repository ) { val unit = TimeUnit . valueOf ( StringUtils . defaultString ( repository . getTimeUnit ( ) , DEFAULT_CACHE_EXPIRATION_UNIT ) ) ; return Caffeine . newBuilder ( ) . initialCapacity ( DEFAULT_MAXIMUM_CACHE_SIZE ) . maximumSize ( DEFAULT_MAXIMUM_CACHE_SIZE ) . expireAfterWrite ( repository . getExpiration ( ) , unit ) . build ( s -> new TreeMap < > ( String . CASE_INSENSITIVE_ORDER ) ) ; } | Initialize cache cache . |
17,831 | public NameID getNameID ( final String nameIdFormat , final String nameIdValue ) { val nameId = newSamlObject ( NameID . class ) ; nameId . setFormat ( nameIdFormat ) ; nameId . setValue ( nameIdValue ) ; return nameId ; } | Gets name id . |
17,832 | public org . opensaml . saml . saml2 . ecp . Response newEcpResponse ( final String assertionConsumerUrl ) { val samlResponse = newSamlObject ( org . opensaml . saml . saml2 . ecp . Response . class ) ; samlResponse . setSOAP11MustUnderstand ( Boolean . TRUE ) ; samlResponse . setSOAP11Actor ( ActorBearing . SOAP11_ACTOR_NEXT ) ; samlResponse . setAssertionConsumerServiceURL ( assertionConsumerUrl ) ; return samlResponse ; } | Create a new SAML ECP response object . |
17,833 | public LogoutRequest newLogoutRequest ( final String id , final DateTime issueInstant , final String destination , final Issuer issuer , final String sessionIndex , final NameID nameId ) { val request = newSamlObject ( LogoutRequest . class ) ; request . setID ( id ) ; request . setVersion ( SAMLVersion . VERSION_20 ) ; request . setIssueInstant ( issueInstant ) ; request . setIssuer ( issuer ) ; request . setDestination ( destination ) ; if ( StringUtils . isNotBlank ( sessionIndex ) ) { val sessionIdx = newSamlObject ( SessionIndex . class ) ; sessionIdx . setSessionIndex ( sessionIndex ) ; request . getSessionIndexes ( ) . add ( sessionIdx ) ; } if ( nameId != null ) { request . setNameID ( nameId ) ; } return request ; } | New saml2 logout request . |
17,834 | public Issuer newIssuer ( final String issuerValue ) { val issuer = newSamlObject ( Issuer . class ) ; issuer . setValue ( issuerValue ) ; return issuer ; } | New issuer . |
17,835 | public AttributeStatement newAttributeStatement ( final Map < String , Object > attributes , final Map < String , String > attributeFriendlyNames , final Map < String , String > attributeValueTypes , final Map < String , String > configuredNameFormats , final String defaultNameFormat ) { return newAttributeStatement ( attributes , attributeFriendlyNames , attributeValueTypes , configuredNameFormats , defaultNameFormat , new DefaultSaml20AttributeBuilder ( ) ) ; } | New attribute statement attribute statement . |
17,836 | public void addAttributeValuesToSaml2Attribute ( final String attributeName , final Object attributeValue , final String valueType , final List < XMLObject > attributeList ) { addAttributeValuesToSamlAttribute ( attributeName , attributeValue , valueType , attributeList , AttributeValue . DEFAULT_ELEMENT_NAME ) ; } | Add saml2 attribute values for attribute . |
17,837 | protected Attribute newAttribute ( final String attributeFriendlyName , final String attributeName , final Object attributeValue , final Map < String , String > configuredNameFormats , final String defaultNameFormat , final Map < String , String > attributeValueTypes ) { val attribute = newSamlObject ( Attribute . class ) ; attribute . setName ( attributeName ) ; if ( StringUtils . isNotBlank ( attributeFriendlyName ) ) { attribute . setFriendlyName ( attributeFriendlyName ) ; } else { attribute . setFriendlyName ( attributeName ) ; } val valueType = attributeValueTypes . get ( attributeName ) ; addAttributeValuesToSaml2Attribute ( attributeName , attributeValue , valueType , attribute . getAttributeValues ( ) ) ; if ( ! configuredNameFormats . isEmpty ( ) && configuredNameFormats . containsKey ( attribute . getName ( ) ) ) { val nameFormat = configuredNameFormats . get ( attribute . getName ( ) ) ; LOGGER . debug ( "Found name format [{}] for attribute [{}]" , nameFormat , attribute . getName ( ) ) ; configureAttributeNameFormat ( attribute , nameFormat ) ; LOGGER . debug ( "Attribute [{}] is assigned the name format of [{}]" , attribute . getName ( ) , attribute . getNameFormat ( ) ) ; } else { LOGGER . debug ( "Skipped name format, as no name formats are defined or none is found for attribute [{}]" , attribute . getName ( ) ) ; configureAttributeNameFormat ( attribute , defaultNameFormat ) ; } LOGGER . debug ( "Attribute [{}] has [{}] value(s)" , attribute . getName ( ) , attribute . getAttributeValues ( ) . size ( ) ) ; return attribute ; } | New attribute . |
17,838 | public AuthnStatement newAuthnStatement ( final String contextClassRef , final ZonedDateTime authnInstant , final String sessionIndex ) { LOGGER . trace ( "Building authentication statement with context class ref [{}] @ [{}] with index [{}]" , contextClassRef , authnInstant , sessionIndex ) ; val stmt = newSamlObject ( AuthnStatement . class ) ; val ctx = newSamlObject ( AuthnContext . class ) ; val classRef = newSamlObject ( AuthnContextClassRef . class ) ; classRef . setAuthnContextClassRef ( contextClassRef ) ; ctx . setAuthnContextClassRef ( classRef ) ; stmt . setAuthnContext ( ctx ) ; stmt . setAuthnInstant ( DateTimeUtils . dateTimeOf ( authnInstant ) ) ; stmt . setSessionIndex ( sessionIndex ) ; return stmt ; } | New authn statement . |
17,839 | public Subject newSubject ( final String nameIdFormat , final String nameIdValue , final String recipient , final ZonedDateTime notOnOrAfter , final String inResponseTo , final ZonedDateTime notBefore ) { val nameID = getNameID ( nameIdFormat , nameIdValue ) ; return newSubject ( nameID , null , recipient , notOnOrAfter , inResponseTo , notBefore ) ; } | New subject subject . |
17,840 | public Subject newSubject ( final NameID nameId , final NameID subjectConfNameId , final String recipient , final ZonedDateTime notOnOrAfter , final String inResponseTo , final ZonedDateTime notBefore ) { LOGGER . debug ( "Building subject for NameID [{}] and recipient [{}], in response to [{}]" , nameId , recipient , inResponseTo ) ; val confirmation = newSamlObject ( SubjectConfirmation . class ) ; confirmation . setMethod ( SubjectConfirmation . METHOD_BEARER ) ; val data = newSamlObject ( SubjectConfirmationData . class ) ; if ( StringUtils . isNotBlank ( recipient ) ) { data . setRecipient ( recipient ) ; } if ( notOnOrAfter != null ) { data . setNotOnOrAfter ( DateTimeUtils . dateTimeOf ( notOnOrAfter ) ) ; } if ( StringUtils . isNotBlank ( inResponseTo ) ) { data . setInResponseTo ( inResponseTo ) ; val ip = InetAddressUtils . getByName ( inResponseTo ) ; if ( ip != null ) { data . setAddress ( ip . getHostName ( ) ) ; } } if ( notBefore != null ) { data . setNotBefore ( DateTimeUtils . dateTimeOf ( notBefore ) ) ; } confirmation . setSubjectConfirmationData ( data ) ; val subject = newSamlObject ( Subject . class ) ; if ( nameId != null ) { subject . setNameID ( nameId ) ; if ( subjectConfNameId != null ) { confirmation . setNameID ( subjectConfNameId ) ; } subject . setEncryptedID ( null ) ; confirmation . setEncryptedID ( null ) ; } subject . getSubjectConfirmations ( ) . add ( confirmation ) ; LOGGER . debug ( "Built subject [{}]" , subject ) ; return subject ; } | New subject element . |
17,841 | public String decodeSamlAuthnRequest ( final String encodedRequestXmlString ) { if ( StringUtils . isEmpty ( encodedRequestXmlString ) ) { return null ; } val decodedBytes = EncodingUtils . decodeBase64 ( encodedRequestXmlString ) ; if ( decodedBytes == null ) { return null ; } return inflateAuthnRequest ( decodedBytes ) ; } | Decode authn request xml . |
17,842 | protected String inflateAuthnRequest ( final byte [ ] decodedBytes ) { val inflated = CompressionUtils . inflate ( decodedBytes ) ; if ( ! StringUtils . isEmpty ( inflated ) ) { return inflated ; } return CompressionUtils . decodeByteArrayToString ( decodedBytes ) ; } | Inflate authn request string . |
17,843 | public void handleRegisteredServicesLoadedEvent ( final CasRegisteredServicesLoadedEvent event ) { event . getServices ( ) . stream ( ) . filter ( OidcRegisteredService . class :: isInstance ) . forEach ( s -> { LOGGER . trace ( "Attempting to reconcile scopes and attributes for service [{}] of type [{}]" , s . getServiceId ( ) , s . getClass ( ) . getSimpleName ( ) ) ; this . scopeToAttributesFilter . reconcile ( s ) ; } ) ; } | Handle registered service loaded event . |
17,844 | public static void bindCurrent ( final Credential ... credentials ) { CURRENT_CREDENTIAL_IDS . set ( Arrays . stream ( credentials ) . map ( Credential :: getId ) . toArray ( String [ ] :: new ) ) ; } | Bind credentials to ThreadLocal . |
17,845 | public static Map < String , Object > getRuntimeProperties ( final Boolean embeddedContainerActive ) { val properties = new HashMap < String , Object > ( ) ; properties . put ( EMBEDDED_CONTAINER_CONFIG_ACTIVE , embeddedContainerActive ) ; return properties ; } | Gets runtime properties . |
17,846 | public static Banner getCasBannerInstance ( ) { val packageName = CasEmbeddedContainerUtils . class . getPackage ( ) . getName ( ) ; val reflections = new Reflections ( new ConfigurationBuilder ( ) . filterInputsBy ( new FilterBuilder ( ) . includePackage ( packageName ) ) . setUrls ( ClasspathHelper . forPackage ( packageName ) ) . setScanners ( new SubTypesScanner ( true ) ) ) ; val subTypes = reflections . getSubTypesOf ( AbstractCasBanner . class ) ; subTypes . remove ( DefaultCasBanner . class ) ; if ( subTypes . isEmpty ( ) ) { return new DefaultCasBanner ( ) ; } try { val clz = subTypes . iterator ( ) . next ( ) ; return clz . getDeclaredConstructor ( ) . newInstance ( ) ; } catch ( final Exception e ) { LOGGER . error ( e . getMessage ( ) , e ) ; } return new DefaultCasBanner ( ) ; } | Gets cas banner instance . |
17,847 | public static < T > T executeGroovyShellScript ( final String script , final Map < String , Object > variables , final Class < T > clazz ) { try { val binding = new Binding ( ) ; val shell = new GroovyShell ( binding ) ; if ( variables != null && ! variables . isEmpty ( ) ) { variables . forEach ( binding :: setVariable ) ; } if ( ! binding . hasVariable ( "logger" ) ) { binding . setVariable ( "logger" , LOGGER ) ; } LOGGER . debug ( "Executing groovy script [{}] with variables [{}]" , script , binding . getVariables ( ) ) ; val result = shell . evaluate ( script ) ; return getGroovyScriptExecutionResultOrThrow ( clazz , result ) ; } catch ( final Exception e ) { LOGGER . error ( e . getMessage ( ) , e ) ; } return null ; } | Execute groovy shell script t . |
17,848 | public static < T > T executeGroovyScript ( final Resource groovyScript , final Object [ ] args , final Class < T > clazz , final boolean failOnError ) { return executeGroovyScript ( groovyScript , "run" , args , clazz , failOnError ) ; } | Execute groovy script via run object . |
17,849 | public static GroovyObject parseGroovyScript ( final Resource groovyScript , final boolean failOnError ) { return AccessController . doPrivileged ( ( PrivilegedAction < GroovyObject > ) ( ) -> { val parent = ScriptingUtils . class . getClassLoader ( ) ; try ( val loader = new GroovyClassLoader ( parent ) ) { val groovyFile = groovyScript . getFile ( ) ; if ( groovyFile . exists ( ) ) { val groovyClass = loader . parseClass ( groovyFile ) ; LOGGER . trace ( "Creating groovy object instance from class [{}]" , groovyFile . getCanonicalPath ( ) ) ; return ( GroovyObject ) groovyClass . getDeclaredConstructor ( ) . newInstance ( ) ; } LOGGER . trace ( "Groovy script at [{}] does not exist" , groovyScript ) ; } catch ( final Exception e ) { if ( failOnError ) { throw new RuntimeException ( e ) ; } LOGGER . error ( e . getMessage ( ) , e ) ; } return null ; } ) ; } | Parse groovy script groovy object . |
17,850 | public static < T > T executeScriptEngine ( final String scriptFile , final Object [ ] args , final Class < T > clazz ) { try { val engineName = getScriptEngineName ( scriptFile ) ; val engine = new ScriptEngineManager ( ) . getEngineByName ( engineName ) ; if ( engine == null || StringUtils . isBlank ( engineName ) ) { LOGGER . warn ( "Script engine is not available for [{}]" , engineName ) ; return null ; } val resourceFrom = ResourceUtils . getResourceFrom ( scriptFile ) ; val theScriptFile = resourceFrom . getFile ( ) ; if ( theScriptFile . exists ( ) ) { LOGGER . debug ( "Created object instance from class [{}]" , theScriptFile . getCanonicalPath ( ) ) ; try ( val reader = Files . newBufferedReader ( theScriptFile . toPath ( ) , StandardCharsets . UTF_8 ) ) { engine . eval ( reader ) ; } val invocable = ( Invocable ) engine ; LOGGER . debug ( "Executing script's run method, with parameters [{}]" , args ) ; val result = invocable . invokeFunction ( "run" , args ) ; LOGGER . debug ( "Groovy script result is [{}]" , result ) ; return getGroovyScriptExecutionResultOrThrow ( clazz , result ) ; } LOGGER . warn ( "[{}] script [{}] does not exist, or cannot be loaded" , StringUtils . capitalize ( engineName ) , scriptFile ) ; } catch ( final Exception e ) { LOGGER . error ( e . getMessage ( ) , e ) ; } return null ; } | Execute groovy script engine t . |
17,851 | public static < T > T executeGroovyScriptEngine ( final String script , final Map < String , Object > variables , final Class < T > clazz ) { try { val engine = new ScriptEngineManager ( ) . getEngineByName ( "groovy" ) ; if ( engine == null ) { LOGGER . warn ( "Script engine is not available for Groovy" ) ; return null ; } val binding = new SimpleBindings ( ) ; if ( variables != null && ! variables . isEmpty ( ) ) { binding . putAll ( variables ) ; } if ( ! binding . containsKey ( "logger" ) ) { binding . put ( "logger" , LOGGER ) ; } val result = engine . eval ( script , binding ) ; return getGroovyScriptExecutionResultOrThrow ( clazz , result ) ; } catch ( final Exception e ) { LOGGER . error ( e . getMessage ( ) , e ) ; } return null ; } | Execute inline groovy script engine . |
17,852 | protected String getResourceSetUriLocation ( final ResourceSet saved ) { return getUmaConfigurationContext ( ) . getCasProperties ( ) . getAuthn ( ) . getUma ( ) . getIssuer ( ) + OAuth20Constants . BASE_OAUTH20_URL + '/' + OAuth20Constants . UMA_RESOURCE_SET_REGISTRATION_URL + '/' + saved . getId ( ) ; } | Gets resource set uri location . |
17,853 | public void validateWsFederationAuthenticationRequest ( final RequestContext context ) { val service = wsFederationCookieManager . retrieve ( context ) ; LOGGER . debug ( "Retrieved service [{}] from the session cookie" , service ) ; val request = WebUtils . getHttpServletRequestFromExternalWebflowContext ( context ) ; val wResult = request . getParameter ( WRESULT ) ; LOGGER . debug ( "Parameter [{}] received: [{}]" , WRESULT , wResult ) ; if ( StringUtils . isBlank ( wResult ) ) { LOGGER . error ( "No [{}] parameter is found" , WRESULT ) ; throw new IllegalArgumentException ( "Missing parameter " + WRESULT ) ; } LOGGER . debug ( "Attempting to create an assertion from the token parameter" ) ; val rsToken = wsFederationHelper . getRequestSecurityTokenFromResult ( wResult ) ; val assertion = wsFederationHelper . buildAndVerifyAssertion ( rsToken , configurations ) ; if ( assertion == null ) { LOGGER . error ( "Could not validate assertion via parsing the token from [{}]" , WRESULT ) ; throw new IllegalArgumentException ( "Could not validate assertion via the provided token" ) ; } LOGGER . debug ( "Attempting to validate the signature on the assertion" ) ; if ( ! wsFederationHelper . validateSignature ( assertion ) ) { val msg = "WS Requested Security Token is blank or the signature is not valid." ; LOGGER . error ( msg ) ; throw new IllegalArgumentException ( msg ) ; } buildCredentialsFromAssertion ( context , assertion , service ) ; } | Validate ws federation authentication request event . |
17,854 | protected void createTransitionStateToAcceptableUsagePolicy ( final Flow flow ) { val submit = getRealSubmissionState ( flow ) ; createTransitionForState ( submit , CasWebflowConstants . TRANSITION_ID_SUCCESS , STATE_ID_AUP_CHECK , true ) ; } | Create transition state to acceptable usage policy . |
17,855 | protected void createSubmitActionState ( final Flow flow ) { val aupAcceptedAction = createActionState ( flow , AUP_ACCEPTED_ACTION , "acceptableUsagePolicySubmitAction" ) ; val target = getRealSubmissionState ( flow ) . getTransition ( CasWebflowConstants . TRANSITION_ID_SUCCESS ) . getTargetStateId ( ) ; val transitionSet = aupAcceptedAction . getTransitionSet ( ) ; transitionSet . add ( createTransition ( CasWebflowConstants . TRANSITION_ID_AUP_ACCEPTED , target ) ) ; transitionSet . add ( createTransition ( CasWebflowConstants . TRANSITION_ID_ERROR , CasWebflowConstants . STATE_ID_INIT_LOGIN_FORM ) ) ; } | Create submit action state . |
17,856 | protected void createAcceptableUsagePolicyView ( final Flow flow ) { val viewState = createViewState ( flow , VIEW_ID_ACCEPTABLE_USAGE_POLICY_VIEW , "casAcceptableUsagePolicyView" ) ; createTransitionForState ( viewState , CasWebflowConstants . TRANSITION_ID_SUBMIT , AUP_ACCEPTED_ACTION ) ; } | Create acceptable usage policy view . |
17,857 | protected void createVerifyActionState ( final Flow flow ) { val actionState = createActionState ( flow , STATE_ID_AUP_CHECK , AUP_VERIFY_ACTION ) ; val transitionSet = actionState . getTransitionSet ( ) ; val target = getRealSubmissionState ( flow ) . getTransition ( CasWebflowConstants . TRANSITION_ID_SUCCESS ) . getTargetStateId ( ) ; transitionSet . add ( createTransition ( CasWebflowConstants . TRANSITION_ID_AUP_ACCEPTED , target ) ) ; transitionSet . add ( createTransition ( CasWebflowConstants . TRANSITION_ID_AUP_MUST_ACCEPT , VIEW_ID_ACCEPTABLE_USAGE_POLICY_VIEW ) ) ; val ticketCreateState = getState ( flow , CasWebflowConstants . STATE_ID_CREATE_TICKET_GRANTING_TICKET , ActionState . class ) ; createEvaluateActionForExistingActionState ( flow , ticketCreateState . getId ( ) , AUP_VERIFY_ACTION ) ; createTransitionForState ( ticketCreateState , CasWebflowConstants . TRANSITION_ID_AUP_MUST_ACCEPT , VIEW_ID_ACCEPTABLE_USAGE_POLICY_VIEW ) ; } | Create verify action state . |
17,858 | public static String deflate ( final byte [ ] bytes ) { val data = new String ( bytes , StandardCharsets . UTF_8 ) ; return deflate ( data ) ; } | Deflate the given bytes using zlib . |
17,859 | public static String decompress ( final String zippedBase64Str ) { val bytes = EncodingUtils . decodeBase64 ( zippedBase64Str ) ; try ( val zi = new GZIPInputStream ( new ByteArrayInputStream ( bytes ) ) ) { return IOUtils . toString ( zi , Charset . defaultCharset ( ) ) ; } } | First decode base64 String to byte array then use ZipInputStream to revert the byte array to a string . |
17,860 | public static String compress ( final String srcTxt ) { try ( val rstBao = new ByteArrayOutputStream ( ) ; val zos = new GZIPOutputStream ( rstBao ) ) { zos . write ( srcTxt . getBytes ( StandardCharsets . UTF_8 ) ) ; zos . flush ( ) ; zos . finish ( ) ; val bytes = rstBao . toByteArray ( ) ; val base64 = StringUtils . remove ( EncodingUtils . encodeBase64 ( bytes ) , '\0' ) ; return new String ( StandardCharsets . UTF_8 . encode ( base64 ) . array ( ) , StandardCharsets . UTF_8 ) ; } } | Use ZipOutputStream to zip text to byte array then convert byte array to base64 string so it can be transferred via http request . |
17,861 | private static void writeObjectByReflection ( final Kryo kryo , final Output output , final Object obj ) { val className = obj . getClass ( ) . getCanonicalName ( ) ; kryo . writeObject ( output , className ) ; kryo . writeObject ( output , obj ) ; } | Write object by reflection . |
17,862 | private static < T > T readObjectByReflection ( final Kryo kryo , final Input input , final Class < T > clazz ) { val className = kryo . readObject ( input , String . class ) ; val foundClass = ( Class < T > ) Class . forName ( className ) ; val result = kryo . readObject ( input , foundClass ) ; if ( ! clazz . isAssignableFrom ( result . getClass ( ) ) ) { throw new ClassCastException ( "Result [" + result + " is of type " + result . getClass ( ) + " when we were expecting " + clazz ) ; } return result ; } | Read object by reflection . |
17,863 | public static byte [ ] serializeAndEncodeObject ( final CipherExecutor cipher , final Serializable object , final Object [ ] parameters ) { val outBytes = serialize ( object ) ; return ( byte [ ] ) cipher . encode ( outBytes , parameters ) ; } | Serialize and encode object . |
17,864 | public static < T extends Serializable > T decodeAndDeserializeObject ( final byte [ ] object , final CipherExecutor cipher , final Class < T > type ) { return decodeAndDeserializeObject ( object , cipher , type , ArrayUtils . EMPTY_OBJECT_ARRAY ) ; } | Decode and deserialize object t . |
17,865 | public Collection < GitObject > getObjectsInRepository ( final TreeFilter filter ) { val repository = this . gitInstance . getRepository ( ) ; val head = repository . resolve ( Constants . HEAD ) ; try ( val walk = new RevWalk ( repository ) ) { val commit = walk . parseCommit ( head ) ; val tree = commit . getTree ( ) ; try ( val treeWalk = new TreeWalk ( repository ) ) { treeWalk . addTree ( tree ) ; treeWalk . setRecursive ( true ) ; treeWalk . setFilter ( filter ) ; val list = new ArrayList < GitObject > ( ) ; while ( treeWalk . next ( ) ) { val object = readObject ( treeWalk ) ; list . add ( object ) ; } return list ; } } } | Gets objects in repository . |
17,866 | public GitObject readObject ( final TreeWalk treeWalk ) { val objectId = treeWalk . getObjectId ( 0 ) ; val repository = this . gitInstance . getRepository ( ) ; val loader = repository . open ( objectId ) ; val out = new ByteArrayOutputStream ( ) ; loader . copyTo ( out ) ; return GitObject . builder ( ) . content ( out . toString ( StandardCharsets . UTF_8 ) ) . treeWalk ( treeWalk ) . objectId ( objectId ) . build ( ) ; } | Read object . |
17,867 | public void commitAll ( final String message ) { this . gitInstance . add ( ) . addFilepattern ( "." ) . call ( ) ; this . gitInstance . commit ( ) . setMessage ( message ) . setAll ( true ) . setAuthor ( "CAS" , "cas@apereo.org" ) . call ( ) ; } | Commit all . |
17,868 | public boolean pull ( ) { val remotes = this . gitInstance . getRepository ( ) . getRemoteNames ( ) ; if ( ! remotes . isEmpty ( ) ) { return this . gitInstance . pull ( ) . setTimeout ( TIMEOUT_SECONDS ) . setFastForward ( MergeCommand . FastForwardMode . FF_ONLY ) . setRebase ( false ) . setProgressMonitor ( new LoggingGitProgressMonitor ( ) ) . call ( ) . isSuccessful ( ) ; } return false ; } | Pull repository changes . |
17,869 | private static Date getExpireAt ( final Ticket ticket ) { val expirationPolicy = ticket . getExpirationPolicy ( ) ; val ttl = ticket instanceof TicketState ? expirationPolicy . getTimeToLive ( ( TicketState ) ticket ) : expirationPolicy . getTimeToLive ( ) ; if ( ttl < 1 ) { return null ; } return new Date ( System . currentTimeMillis ( ) + TimeUnit . SECONDS . toMillis ( ttl ) ) ; } | Calculate the time at which the ticket is eligible for automated deletion by MongoDb . Makes the assumption that the CAS server date and the Mongo server date are in sync . |
17,870 | private static void removeDifferingIndexIfAny ( final MongoCollection collection , final Index index ) { val indexes = ( ListIndexesIterable < Document > ) collection . listIndexes ( ) ; var indexExistsWithDifferentOptions = false ; for ( val existingIndex : indexes ) { val keyMatches = existingIndex . get ( "key" ) . equals ( index . getIndexKeys ( ) ) ; val optionsMatch = index . getIndexOptions ( ) . entrySet ( ) . stream ( ) . allMatch ( entry -> entry . getValue ( ) . equals ( existingIndex . get ( entry . getKey ( ) ) ) ) ; val noExtraOptions = existingIndex . keySet ( ) . stream ( ) . allMatch ( key -> MONGO_INDEX_KEYS . contains ( key ) || index . getIndexOptions ( ) . keySet ( ) . contains ( key ) ) ; indexExistsWithDifferentOptions |= keyMatches && ! ( optionsMatch && noExtraOptions ) ; } if ( indexExistsWithDifferentOptions ) { LOGGER . debug ( "Removing MongoDb index [{}] from [{}] because it appears to already exist in a different form" , index . getIndexKeys ( ) , collection . getNamespace ( ) ) ; collection . dropIndex ( index . getIndexKeys ( ) ) ; } } | Remove any index with the same indexKey but differing indexOptions in anticipation of recreating it . |
17,871 | protected static boolean locateMatchingAttributeValue ( final String attrName , final String attrValue , final Map < String , List < Object > > attributes ) { return locateMatchingAttributeValue ( attrName , attrValue , attributes , true ) ; } | Locate matching attribute value boolean . |
17,872 | protected static boolean locateMatchingAttributeValue ( final String attrName , final String attrValue , final Map < String , List < Object > > attributes , final boolean matchIfNoValueProvided ) { LOGGER . debug ( "Locating matching attribute [{}] with value [{}] amongst the attribute collection [{}]" , attrName , attrValue , attributes ) ; if ( StringUtils . isBlank ( attrName ) ) { LOGGER . debug ( "Failed to match since attribute name is undefined" ) ; return false ; } val names = attributes . entrySet ( ) . stream ( ) . filter ( e -> { LOGGER . debug ( "Attempting to match [{}] against [{}]" , attrName , e . getKey ( ) ) ; return e . getKey ( ) . matches ( attrName ) ; } ) . collect ( Collectors . toSet ( ) ) ; LOGGER . debug ( "Found [{}] attributes relevant for multifactor authentication bypass" , names . size ( ) ) ; if ( names . isEmpty ( ) ) { return false ; } if ( StringUtils . isBlank ( attrValue ) ) { LOGGER . debug ( "No attribute value to match is provided; Match result is set to [{}]" , matchIfNoValueProvided ) ; return matchIfNoValueProvided ; } val values = names . stream ( ) . filter ( e -> { val valuesCol = CollectionUtils . toCollection ( e . getValue ( ) ) ; LOGGER . debug ( "Matching attribute [{}] with values [{}] against [{}]" , e . getKey ( ) , valuesCol , attrValue ) ; return valuesCol . stream ( ) . anyMatch ( v -> v . toString ( ) . matches ( attrValue ) ) ; } ) . collect ( Collectors . toSet ( ) ) ; LOGGER . debug ( "Matching attribute values remaining are [{}]" , values ) ; return ! values . isEmpty ( ) ; } | Evaluate attribute rules for bypass . |
17,873 | public CouchDbMultifactorAuthenticationTrustRecord merge ( final MultifactorAuthenticationTrustRecord other ) { setId ( other . getId ( ) ) ; setPrincipal ( other . getPrincipal ( ) ) ; setDeviceFingerprint ( other . getDeviceFingerprint ( ) ) ; setRecordDate ( other . getRecordDate ( ) ) ; setRecordKey ( other . getRecordKey ( ) ) ; setName ( other . getName ( ) ) ; return this ; } | Merge other record into this one for updating . |
17,874 | public PropertiesFactoryBean casCommonMessages ( ) { val properties = new PropertiesFactoryBean ( ) ; val resourceLoader = new DefaultResourceLoader ( ) ; val commonNames = casProperties . getMessageBundle ( ) . getCommonNames ( ) ; val resourceList = commonNames . stream ( ) . map ( resourceLoader :: getResource ) . collect ( Collectors . toList ( ) ) ; resourceList . add ( resourceLoader . getResource ( "classpath:/cas_common_messages.properties" ) ) ; properties . setLocations ( resourceList . toArray ( Resource [ ] :: new ) ) ; properties . setSingleton ( true ) ; properties . setIgnoreResourceNotFound ( true ) ; return properties ; } | Load property files containing non - i18n fallback values that should be exposed to Thyme templates . keys in properties files added last will take precedence over the internal cas_common_messages . properties . Keys in regular messages bundles will override any of the common messages . |
17,875 | protected Http buildHttpPostAuthRequest ( ) { return new Http ( HttpMethod . POST . name ( ) , duoProperties . getDuoApiHost ( ) , String . format ( "/auth/v%s/auth" , AUTH_API_VERSION ) ) ; } | Build http post auth request http . |
17,876 | protected Http buildHttpPostUserPreAuthRequest ( final String username ) { val usersRequest = new Http ( HttpMethod . POST . name ( ) , duoProperties . getDuoApiHost ( ) , String . format ( "/auth/v%s/preauth" , AUTH_API_VERSION ) ) ; usersRequest . addParam ( "username" , username ) ; return usersRequest ; } | Build http post get user auth request . |
17,877 | protected Http signHttpAuthRequest ( final Http request , final String id ) { request . addParam ( "username" , id ) ; request . addParam ( "factor" , "auto" ) ; request . addParam ( "device" , "auto" ) ; request . signRequest ( duoProperties . getDuoIntegrationKey ( ) , duoProperties . getDuoSecretKey ( ) ) ; return request ; } | Sign http request . |
17,878 | protected Http signHttpUserPreAuthRequest ( final Http request ) { request . signRequest ( duoProperties . getDuoIntegrationKey ( ) , duoProperties . getDuoSecretKey ( ) ) ; return request ; } | Sign http users request http . |
17,879 | @ GetMapping ( path = SamlIdPConstants . ENDPOINT_SAML2_SLO_PROFILE_REDIRECT ) protected void handleSaml2ProfileSLOPostRequest ( final HttpServletResponse response , final HttpServletRequest request ) throws Exception { val decoder = getSamlProfileHandlerConfigurationContext ( ) . getSamlMessageDecoders ( ) . getInstance ( HttpMethod . GET ) ; handleSloProfileRequest ( response , request , decoder ) ; } | Handle SLO Redirect profile request . |
17,880 | public N1qlQueryResult query ( final String usernameAttribute , final String usernameValue ) throws GeneralSecurityException { val theBucket = getBucket ( ) ; val statement = Select . select ( "*" ) . from ( Expression . i ( theBucket . name ( ) ) ) . where ( Expression . x ( usernameAttribute ) . eq ( '\'' + usernameValue + '\'' ) ) ; LOGGER . debug ( "Running query [{}] on bucket [{}]" , statement . toString ( ) , theBucket . name ( ) ) ; val query = N1qlQuery . simple ( statement ) ; val result = theBucket . query ( query , timeout , TimeUnit . MILLISECONDS ) ; if ( ! result . finalSuccess ( ) ) { LOGGER . error ( "Couchbase query failed with [{}]" , result . errors ( ) . stream ( ) . map ( JsonObject :: toString ) . collect ( Collectors . joining ( "," ) ) ) ; throw new GeneralSecurityException ( "Could not locate account for user " + usernameValue ) ; } return result ; } | Query and get a result by username . |
17,881 | public Map < String , List < Object > > collectAttributesFromEntity ( final JsonObject couchbaseEntity , final Predicate < String > filter ) { return couchbaseEntity . getNames ( ) . stream ( ) . filter ( filter ) . map ( name -> Pair . of ( name , couchbaseEntity . get ( name ) ) ) . collect ( Collectors . toMap ( Pair :: getKey , s -> CollectionUtils . wrapList ( s . getValue ( ) ) ) ) ; } | Collect attributes from entity map . |
17,882 | protected Event finalizeResponseEvent ( final RequestContext requestContext , final WebApplicationService service , final Response response ) { WebUtils . putServiceResponseIntoRequestScope ( requestContext , response ) ; WebUtils . putServiceOriginalUrlIntoRequestScope ( requestContext , service ) ; val eventId = getFinalResponseEventId ( service , response , requestContext ) ; return new EventFactorySupport ( ) . event ( this , eventId ) ; } | Finalize response event event . |
17,883 | protected String getFinalResponseEventId ( final WebApplicationService service , final Response response , final RequestContext requestContext ) { val eventId = response . getResponseType ( ) . name ( ) . toLowerCase ( ) ; LOGGER . debug ( "Signaling flow to redirect to service [{}] via event [{}]" , service , eventId ) ; return eventId ; } | Gets final response event id . |
17,884 | private static boolean isTokenNtlm ( final byte [ ] token ) { if ( token == null || token . length < NTLM_TOKEN_MAX_LENGTH ) { return false ; } return IntStream . range ( 0 , NTLM_TOKEN_MAX_LENGTH ) . noneMatch ( i -> NTLMSSP_SIGNATURE [ i ] != token [ i ] ) ; } | Checks if is token ntlm . |
17,885 | private static byte [ ] consumeByteSourceOrNull ( final ByteSource source ) { try { if ( source == null || source . isEmpty ( ) ) { return null ; } return source . read ( ) ; } catch ( final IOException e ) { LOGGER . warn ( "Could not consume the byte array source" , e ) ; return null ; } } | Read the contents of the source into a byte array . |
17,886 | public WebSecurityConfigurerAdapter casConfigurationServerWebSecurityConfigurerAdapter ( final ServerProperties serverProperties ) { return new WebSecurityConfigurerAdapter ( ) { protected void configure ( final HttpSecurity http ) throws Exception { super . configure ( http ) ; val path = serverProperties . getServlet ( ) . getContextPath ( ) ; http . authorizeRequests ( ) . antMatchers ( path + "/decrypt/**" ) . authenticated ( ) . and ( ) . csrf ( ) . disable ( ) ; http . authorizeRequests ( ) . antMatchers ( path + "/encrypt/**" ) . authenticated ( ) . and ( ) . csrf ( ) . disable ( ) ; } } ; } | CAS configuration server web security configurer . |
17,887 | @ GetMapping ( produces = MediaType . APPLICATION_XML_VALUE ) public ResponseEntity < Object > produce ( final HttpServletRequest request , final HttpServletResponse response ) { val username = request . getParameter ( "username" ) ; val password = request . getParameter ( "password" ) ; val entityId = request . getParameter ( SamlProtocolConstants . PARAMETER_ENTITY_ID ) ; try { val selectedService = this . serviceFactory . createService ( entityId ) ; val registeredService = this . servicesManager . findServiceBy ( selectedService , SamlRegisteredService . class ) ; RegisteredServiceAccessStrategyUtils . ensureServiceAccessIsAllowed ( registeredService ) ; val assertion = getAssertion ( username , password , entityId ) ; val authnRequest = new AuthnRequestBuilder ( ) . buildObject ( ) ; authnRequest . setIssuer ( saml20ObjectBuilder . newIssuer ( entityId ) ) ; val adaptorResult = SamlRegisteredServiceServiceProviderMetadataFacade . get ( defaultSamlRegisteredServiceCachingMetadataResolver , registeredService , entityId ) ; if ( adaptorResult . isPresent ( ) ) { val adaptor = adaptorResult . get ( ) ; val messageContext = new MessageContext < > ( ) ; val scratch = messageContext . getSubcontext ( ScratchContext . class , true ) ; scratch . getMap ( ) . put ( SamlProtocolConstants . PARAMETER_ENCODE_RESPONSE , Boolean . FALSE ) ; val object = this . responseBuilder . build ( authnRequest , request , response , assertion , registeredService , adaptor , SAMLConstants . SAML2_POST_BINDING_URI , messageContext ) ; val encoded = SamlUtils . transformSamlObject ( saml20ObjectBuilder . getOpenSamlConfigBean ( ) , object ) . toString ( ) ; return new ResponseEntity < > ( encoded , HttpStatus . OK ) ; } } catch ( final Exception e ) { LOGGER . error ( e . getMessage ( ) , e ) ; return new ResponseEntity < > ( e . getMessage ( ) , HttpStatus . BAD_REQUEST ) ; } return new ResponseEntity < > ( HttpStatus . INTERNAL_SERVER_ERROR ) ; } | Produce response entity . |
17,888 | protected long getCacheDurationForServiceProvider ( final SamlRegisteredService service , final MetadataResolver chainingMetadataResolver ) { try { val set = new CriteriaSet ( ) ; set . add ( new EntityIdCriterion ( service . getServiceId ( ) ) ) ; set . add ( new EntityRoleCriterion ( SPSSODescriptor . DEFAULT_ELEMENT_NAME ) ) ; val entitySp = chainingMetadataResolver . resolveSingle ( set ) ; if ( entitySp != null && entitySp . getCacheDuration ( ) != null ) { LOGGER . debug ( "Located cache duration [{}] specified in SP metadata for [{}]" , entitySp . getCacheDuration ( ) , entitySp . getEntityID ( ) ) ; return TimeUnit . MILLISECONDS . toNanos ( entitySp . getCacheDuration ( ) ) ; } set . clear ( ) ; set . add ( new EntityIdCriterion ( service . getServiceId ( ) ) ) ; val entity = chainingMetadataResolver . resolveSingle ( set ) ; if ( entity != null && entity . getCacheDuration ( ) != null ) { LOGGER . debug ( "Located cache duration [{}] specified in entity metadata for [{}]" , entity . getCacheDuration ( ) , entity . getEntityID ( ) ) ; return TimeUnit . MILLISECONDS . toNanos ( entity . getCacheDuration ( ) ) ; } } catch ( final Exception e ) { LOGGER . debug ( e . getMessage ( ) , e ) ; } return - 1 ; } | Gets cache duration for service provider . |
17,889 | private boolean executeModifyOperation ( final Set < String > newConsent , final LdapEntry entry ) { val attrMap = new HashMap < String , Set < String > > ( ) ; attrMap . put ( this . ldap . getConsentAttributeName ( ) , newConsent ) ; LOGGER . debug ( "Storing consent decisions [{}] at LDAP attribute [{}] for [{}]" , newConsent , attrMap . keySet ( ) , entry . getDn ( ) ) ; return LdapUtils . executeModifyOperation ( entry . getDn ( ) , this . connectionFactory , CollectionUtils . wrap ( attrMap ) ) ; } | Modifies the consent decisions attribute on the entry . |
17,890 | private static Set < String > mergeDecision ( final LdapAttribute ldapConsent , final ConsentDecision decision ) { if ( decision . getId ( ) < 0 ) { decision . setId ( System . currentTimeMillis ( ) ) ; } if ( ldapConsent != null ) { val result = removeDecision ( ldapConsent , decision . getId ( ) ) ; val json = mapToJson ( decision ) ; if ( StringUtils . isBlank ( json ) ) { throw new IllegalArgumentException ( "Could not map consent decision to JSON" ) ; } result . add ( json ) ; LOGGER . debug ( "Merged consent decision [{}] with LDAP attribute [{}]" , decision , ldapConsent . getName ( ) ) ; return CollectionUtils . wrap ( result ) ; } val result = new HashSet < String > ( ) ; val json = mapToJson ( decision ) ; if ( StringUtils . isBlank ( json ) ) { throw new IllegalArgumentException ( "Could not map consent decision to JSON" ) ; } result . add ( json ) ; return result ; } | Merges a new decision into existing decisions . Decisions are matched by ID . |
17,891 | private static Set < String > removeDecision ( final LdapAttribute ldapConsent , final long decisionId ) { val result = new HashSet < String > ( ) ; if ( ldapConsent . size ( ) != 0 ) { ldapConsent . getStringValues ( ) . stream ( ) . map ( LdapConsentRepository :: mapFromJson ) . filter ( d -> d . getId ( ) != decisionId ) . map ( LdapConsentRepository :: mapToJson ) . filter ( Objects :: nonNull ) . forEach ( result :: add ) ; } return result ; } | Removes decision from ldap attribute set . |
17,892 | private LdapEntry readConsentEntry ( final String principal ) { try { val filter = LdapUtils . newLdaptiveSearchFilter ( this . searchFilter , CollectionUtils . wrapList ( principal ) ) ; LOGGER . debug ( "Locating consent LDAP entry via filter [{}] based on attribute [{}]" , filter , this . ldap . getConsentAttributeName ( ) ) ; val response = LdapUtils . executeSearchOperation ( this . connectionFactory , this . ldap . getBaseDn ( ) , filter , this . ldap . getConsentAttributeName ( ) ) ; if ( LdapUtils . containsResultEntry ( response ) ) { val entry = response . getResult ( ) . getEntry ( ) ; LOGGER . debug ( "Locating consent LDAP entry [{}]" , entry ) ; return entry ; } } catch ( final LdapException e ) { LOGGER . debug ( e . getMessage ( ) , e ) ; } return null ; } | Fetches a user entry along with its consent attributes . |
17,893 | private Collection < LdapEntry > readConsentEntries ( ) { try { val att = this . ldap . getConsentAttributeName ( ) ; val filter = LdapUtils . newLdaptiveSearchFilter ( '(' + att + "=*)" ) ; LOGGER . debug ( "Locating consent LDAP entries via filter [{}] based on attribute [{}]" , filter , att ) ; val response = LdapUtils . executeSearchOperation ( this . connectionFactory , this . ldap . getBaseDn ( ) , filter , att ) ; if ( LdapUtils . containsResultEntry ( response ) ) { val results = response . getResult ( ) . getEntries ( ) ; LOGGER . debug ( "Locating [{}] consent LDAP entries" , results . size ( ) ) ; return results ; } } catch ( final LdapException e ) { LOGGER . debug ( e . getMessage ( ) , e ) ; } return new HashSet < > ( 0 ) ; } | Fetches all user entries that contain consent attributes along with these . |
17,894 | @ View ( name = "by_createdDate" , map = "function(doc) { if(doc.record && doc.createdDate && doc.username) { emit(doc.createdDate, doc) } }" ) public List < CouchDbU2FDeviceRegistration > findByDateBefore ( final LocalDate expirationDate ) { return db . queryView ( createQuery ( "by_createdDate" ) . endKey ( expirationDate ) , CouchDbU2FDeviceRegistration . class ) ; } | Find expired records . |
17,895 | public String buildPasswordResetUrl ( final String username , final PasswordManagementService passwordManagementService , final CasConfigurationProperties casProperties ) { val token = passwordManagementService . createToken ( username ) ; if ( StringUtils . isNotBlank ( token ) ) { val transientFactory = ( TransientSessionTicketFactory ) this . ticketFactory . get ( TransientSessionTicket . class ) ; val serverPrefix = casProperties . getServer ( ) . getPrefix ( ) ; val service = webApplicationServiceFactory . createService ( serverPrefix ) ; val properties = CollectionUtils . < String , Serializable > wrap ( PasswordManagementWebflowUtils . FLOWSCOPE_PARAMETER_NAME_TOKEN , token ) ; val ticket = transientFactory . create ( service , properties ) ; this . ticketRegistry . addTicket ( ticket ) ; return serverPrefix . concat ( '/' + CasWebflowConfigurer . FLOW_ID_LOGIN + '?' + PasswordManagementWebflowUtils . REQUEST_PARAMETER_NAME_PASSWORD_RESET_TOKEN + '=' ) . concat ( ticket . getId ( ) ) ; } LOGGER . error ( "Could not create password reset url since no reset token could be generated" ) ; return null ; } | Utility method to generate a password reset URL . |
17,896 | protected boolean sendPasswordResetEmailToAccount ( final String to , final String url ) { val reset = casProperties . getAuthn ( ) . getPm ( ) . getReset ( ) . getMail ( ) ; val text = reset . getFormattedBody ( url ) ; return this . communicationsManager . email ( reset , to , text ) ; } | Send password reset email to account . |
17,897 | public boolean acquire ( final Lock lock ) { lock . setUniqueId ( this . uniqueId ) ; if ( this . lockTimeout > 0 ) { lock . setExpirationDate ( ZonedDateTime . now ( ZoneOffset . UTC ) . plusSeconds ( this . lockTimeout ) ) ; } else { lock . setExpirationDate ( null ) ; } var success = false ; try { if ( lock . getApplicationId ( ) != null ) { this . entityManager . merge ( lock ) ; } else { lock . setApplicationId ( this . applicationId ) ; this . entityManager . persist ( lock ) ; } success = true ; } catch ( final Exception e ) { success = false ; if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "[{}] could not obtain [{}] lock." , this . uniqueId , this . applicationId , e ) ; } else { LOGGER . info ( "[{}] could not obtain [{}] lock." , this . uniqueId , this . applicationId ) ; } } return success ; } | Acquire the lock object . |
17,898 | protected void handlePolicyAttributes ( final AuthenticationResponse response ) { val attributes = response . getLdapEntry ( ) . getAttributes ( ) ; for ( val attr : attributes ) { if ( this . attributesToErrorMap . containsKey ( attr . getName ( ) ) && Boolean . parseBoolean ( attr . getStringValue ( ) ) ) { val clazz = this . attributesToErrorMap . get ( attr . getName ( ) ) ; throw clazz . getDeclaredConstructor ( ) . newInstance ( ) ; } } } | Maps boolean attribute values to their corresponding exception . This handles ad - hoc password policies . |
17,899 | public RadiusClient newInstance ( ) { return new RadiusClient ( InetAddress . getByName ( this . inetAddress ) , this . sharedSecret , this . authenticationPort , this . accountingPort , this . socketTimeout ) ; } | New instance radius client . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.