idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
18,000
public static Map < String , String > getRequestHeaders ( final HttpServletRequest request ) { val headers = new LinkedHashMap < String , Object > ( ) ; val headerNames = request . getHeaderNames ( ) ; if ( headerNames != null ) { while ( headerNames . hasMoreElements ( ) ) { val headerName = headerNames . nextElement ( ) ; val headerValue = StringUtils . stripToEmpty ( request . getHeader ( headerName ) ) ; headers . put ( headerName , headerValue ) ; } } return ( Map ) headers ; }
Gets request headers .
18,001
public static String getHttpServletRequestUserAgent ( final HttpServletRequest request ) { if ( request != null ) { return request . getHeader ( USER_AGENT_HEADER ) ; } return null ; }
Gets http servlet request user agent .
18,002
public static WebApplicationService getService ( final List < ArgumentExtractor > argumentExtractors , final HttpServletRequest request ) { return argumentExtractors . stream ( ) . map ( argumentExtractor -> argumentExtractor . extractService ( request ) ) . filter ( Objects :: nonNull ) . findFirst ( ) . orElse ( null ) ; }
Gets the service from the request based on given extractors .
18,003
public static boolean doesParameterExist ( final HttpServletRequest request , final String name ) { val parameter = request . getParameter ( name ) ; if ( StringUtils . isBlank ( parameter ) ) { LOGGER . error ( "Missing request parameter: [{}]" , name ) ; return false ; } LOGGER . debug ( "Found provided request parameter [{}]" , name ) ; return true ; }
Check if a parameter exists .
18,004
public static HttpStatus pingUrl ( final String location ) { try { val url = new URL ( location ) ; val connection = ( HttpURLConnection ) url . openConnection ( ) ; connection . setConnectTimeout ( PING_URL_TIMEOUT ) ; connection . setReadTimeout ( PING_URL_TIMEOUT ) ; connection . setRequestMethod ( HttpMethod . HEAD . name ( ) ) ; return HttpStatus . valueOf ( connection . getResponseCode ( ) ) ; } catch ( final Exception e ) { LOGGER . error ( e . getMessage ( ) , e ) ; } return HttpStatus . SERVICE_UNAVAILABLE ; }
Ping url and return http status .
18,005
public static Transcoder newTranscoder ( final BaseMemcachedProperties memcachedProperties , final Collection < Class > kryoSerializableClasses ) { switch ( StringUtils . trimToEmpty ( memcachedProperties . getTranscoder ( ) ) . toLowerCase ( ) ) { case "serial" : val serial = new SerializingTranscoder ( ) ; serial . setCompressionThreshold ( memcachedProperties . getTranscoderCompressionThreshold ( ) ) ; LOGGER . debug ( "Creating memcached transcoder [{}]" , serial . getClass ( ) . getName ( ) ) ; return serial ; case "whalin" : val whalin = new WhalinTranscoder ( ) ; whalin . setCompressionThreshold ( memcachedProperties . getTranscoderCompressionThreshold ( ) ) ; LOGGER . debug ( "Creating memcached transcoder [{}]" , whalin . getClass ( ) . getName ( ) ) ; return whalin ; case "whalinv1" : val whalinv1 = new WhalinV1Transcoder ( ) ; whalinv1 . setCompressionThreshold ( memcachedProperties . getTranscoderCompressionThreshold ( ) ) ; LOGGER . debug ( "Creating memcached transcoder [{}]" , whalinv1 . getClass ( ) . getName ( ) ) ; return whalinv1 ; case "kryo" : default : val kryoPool = new CasKryoPool ( kryoSerializableClasses , true , memcachedProperties . isKryoRegistrationRequired ( ) , memcachedProperties . isKryoObjectsByReference ( ) , memcachedProperties . isKryoAutoReset ( ) ) ; val kryo = new CasKryoTranscoder ( kryoPool ) ; LOGGER . debug ( "Creating memcached transcoder [{}]" , kryo . getClass ( ) . getName ( ) ) ; return kryo ; } }
New transcoder transcoder .
18,006
public static AuditableExecutionResult of ( final AuditableContext context ) { val builder = AuditableExecutionResult . builder ( ) ; context . getTicketGrantingTicket ( ) . ifPresent ( builder :: ticketGrantingTicket ) ; context . getAuthentication ( ) . ifPresent ( builder :: authentication ) ; context . getAuthenticationResult ( ) . ifPresent ( builder :: authenticationResult ) ; context . getRegisteredService ( ) . ifPresent ( builder :: registeredService ) ; context . getService ( ) . ifPresent ( builder :: service ) ; context . getServiceTicket ( ) . ifPresent ( builder :: serviceTicket ) ; builder . properties ( context . getProperties ( ) ) ; return builder . build ( ) ; }
Of auditable execution result .
18,007
protected AbstractMetadataResolver buildMetadataResolverFrom ( final SamlRegisteredService service , final SamlMetadataDocument metadataDocument ) { try { val desc = StringUtils . defaultString ( service . getDescription ( ) , service . getName ( ) ) ; val metadataResource = ResourceUtils . buildInputStreamResourceFrom ( metadataDocument . getDecodedValue ( ) , desc ) ; val metadataResolver = new InMemoryResourceMetadataResolver ( metadataResource , configBean ) ; val metadataFilterList = new ArrayList < MetadataFilter > ( ) ; if ( StringUtils . isNotBlank ( metadataDocument . getSignature ( ) ) ) { val signatureResource = ResourceUtils . buildInputStreamResourceFrom ( metadataDocument . getSignature ( ) , desc ) ; buildSignatureValidationFilterIfNeeded ( service , metadataFilterList , signatureResource ) ; } configureAndInitializeSingleMetadataResolver ( metadataResolver , service , metadataFilterList ) ; return metadataResolver ; } catch ( final Exception e ) { LOGGER . error ( e . getMessage ( ) , e ) ; } return null ; }
Build metadata resolver from document .
18,008
protected void configureAndInitializeSingleMetadataResolver ( final AbstractMetadataResolver metadataProvider , final SamlRegisteredService service , final List < MetadataFilter > metadataFilterList ) throws Exception { val md = samlIdPProperties . getMetadata ( ) ; metadataProvider . setParserPool ( this . configBean . getParserPool ( ) ) ; metadataProvider . setFailFastInitialization ( md . isFailFast ( ) ) ; metadataProvider . setRequireValidMetadata ( md . isRequireValidMetadata ( ) ) ; metadataProvider . setId ( metadataProvider . getClass ( ) . getCanonicalName ( ) ) ; buildMetadataFilters ( service , metadataProvider , metadataFilterList ) ; LOGGER . debug ( "Initializing metadata resolver from [{}]" , service . getMetadataLocation ( ) ) ; metadataProvider . initialize ( ) ; LOGGER . info ( "Initialized metadata resolver from [{}]" , service . getMetadataLocation ( ) ) ; }
Build single metadata resolver metadata resolver .
18,009
protected void configureAndInitializeSingleMetadataResolver ( final AbstractMetadataResolver metadataProvider , final SamlRegisteredService service ) throws Exception { configureAndInitializeSingleMetadataResolver ( metadataProvider , service , new ArrayList < > ( ) ) ; }
Configure and initialize single metadata resolver .
18,010
protected void buildMetadataFilters ( final SamlRegisteredService service , final AbstractMetadataResolver metadataProvider , final List < MetadataFilter > metadataFilterList ) throws Exception { buildRequiredValidUntilFilterIfNeeded ( service , metadataFilterList ) ; buildSignatureValidationFilterIfNeeded ( service , metadataFilterList ) ; buildEntityRoleFilterIfNeeded ( service , metadataFilterList ) ; buildPredicateFilterIfNeeded ( service , metadataFilterList ) ; if ( ! metadataFilterList . isEmpty ( ) ) { addMetadataFiltersToMetadataResolver ( metadataProvider , metadataFilterList ) ; } }
Build metadata filters .
18,011
protected Conditions buildConditions ( final RequestAbstractType authnRequest , final Object assertion , final SamlRegisteredService service , final SamlRegisteredServiceServiceProviderMetadataFacade adaptor , final MessageContext messageContext ) throws SamlException { val currentDateTime = ZonedDateTime . now ( ZoneOffset . UTC ) ; var skewAllowance = casProperties . getAuthn ( ) . getSamlIdp ( ) . getResponse ( ) . getSkewAllowance ( ) ; if ( skewAllowance <= 0 ) { skewAllowance = casProperties . getSamlCore ( ) . getSkewAllowance ( ) ; } val audienceUrls = new ArrayList < String > ( ) ; audienceUrls . add ( adaptor . getEntityId ( ) ) ; if ( StringUtils . isNotBlank ( service . getAssertionAudiences ( ) ) ) { val audiences = org . springframework . util . StringUtils . commaDelimitedListToSet ( service . getAssertionAudiences ( ) ) ; audienceUrls . addAll ( audiences ) ; } return newConditions ( currentDateTime , currentDateTime . plusSeconds ( skewAllowance ) , audienceUrls . toArray ( ArrayUtils . EMPTY_STRING_ARRAY ) ) ; }
Build conditions conditions .
18,012
public static AttributeKeyAndValue getAttributeKeyValueByName ( final ListObjectAttributesResult attributesResult , final String attributeName ) { return attributesResult . getAttributes ( ) . stream ( ) . filter ( a -> a . getKey ( ) . getName ( ) . equalsIgnoreCase ( attributeName ) ) . findFirst ( ) . orElse ( null ) ; }
Gets attribute key value by name .
18,013
public static ListObjectAttributesRequest getListObjectAttributesRequest ( final String arnName , final String objectId ) { return new ListObjectAttributesRequest ( ) . withDirectoryArn ( arnName ) . withObjectReference ( getObjectRefById ( objectId ) ) ; }
Gets list object attributes request .
18,014
public static ObjectReference getObjectRefByPath ( final String path ) { if ( path == null ) { return null ; } return new ObjectReference ( ) . withSelector ( path ) ; }
Gets object ref by path .
18,015
public static ListIndexRequest getListIndexRequest ( final String attributeName , final String attributeValue , final ObjectReference reference , final CloudDirectoryProperties cloud ) { val range = getObjectAttributeRanges ( cloud . getSchemaArn ( ) , cloud . getFacetName ( ) , attributeName , attributeValue ) ; return new ListIndexRequest ( ) . withDirectoryArn ( cloud . getDirectoryArn ( ) ) . withIndexReference ( reference ) . withRangesOnIndexedValues ( range ) ; }
Gets list index request .
18,016
public static ObjectAttributeRange getObjectAttributeRanges ( final String schemaArn , final String facetName , final String attributeName , final String attributeValue ) { val attributeKey = getAttributeKey ( schemaArn , facetName , attributeName ) ; return new ObjectAttributeRange ( ) . withAttributeKey ( attributeKey ) . withRange ( new TypedAttributeValueRange ( ) . withStartValue ( getTypedAttributeValue ( attributeValue ) ) . withEndValue ( getTypedAttributeValue ( attributeValue ) ) . withStartMode ( RangeMode . INCLUSIVE . toString ( ) ) . withEndMode ( RangeMode . INCLUSIVE . toString ( ) ) ) ; }
Gets object attribute ranges .
18,017
private static AttributeKey getAttributeKey ( final String schemaArn , final String facetName , final String attributeName ) { return new AttributeKey ( ) . withFacetName ( facetName ) . withSchemaArn ( schemaArn ) . withName ( attributeName ) ; }
Gets attribute key .
18,018
protected int cleanInternal ( ) { try ( val expiredTickets = ticketRegistry . getTicketsStream ( ) . filter ( Ticket :: isExpired ) ) { val ticketsDeleted = expiredTickets . mapToInt ( this :: cleanTicket ) . sum ( ) ; LOGGER . info ( "[{}] expired tickets removed." , ticketsDeleted ) ; return ticketsDeleted ; } }
Clean tickets .
18,019
protected AbstractMetadataResolver getMetadataResolverFromResponse ( final HttpResponse response , final File backupFile ) throws Exception { val entity = response . getEntity ( ) ; val result = IOUtils . toString ( entity . getContent ( ) , StandardCharsets . UTF_8 ) ; val path = backupFile . toPath ( ) ; LOGGER . trace ( "Writing metadata to file at [{}]" , path ) ; try ( val output = Files . newBufferedWriter ( path , StandardCharsets . UTF_8 ) ) { IOUtils . write ( result , output ) ; output . flush ( ) ; } EntityUtils . consume ( entity ) ; return new InMemoryResourceMetadataResolver ( backupFile , configBean ) ; }
Gets metadata resolver from response .
18,020
protected HttpResponse fetchMetadata ( final String metadataLocation , final CriteriaSet criteriaSet ) { LOGGER . debug ( "Fetching metadata from [{}]" , metadataLocation ) ; return HttpUtils . executeGet ( metadataLocation , new LinkedHashMap < > ( ) ) ; }
Fetch metadata http response .
18,021
protected File getMetadataBackupFile ( final AbstractResource metadataResource , final SamlRegisteredService service ) throws IOException { LOGGER . debug ( "Metadata backup directory is at [{}]" , this . metadataBackupDirectory . getCanonicalPath ( ) ) ; val metadataFileName = getBackupMetadataFilenamePrefix ( metadataResource , service ) . concat ( FILENAME_EXTENSION_XML ) ; val backupFile = new File ( this . metadataBackupDirectory , metadataFileName ) ; if ( backupFile . exists ( ) ) { LOGGER . info ( "Metadata file designated for service [{}] already exists at path [{}]." , service . getName ( ) , backupFile . getCanonicalPath ( ) ) ; } else { LOGGER . debug ( "Metadata to fetch for service [{}] will be placed at [{}]" , service . getName ( ) , backupFile . getCanonicalPath ( ) ) ; } return backupFile ; }
Gets metadata backup file .
18,022
public SecurityTokenServiceClient buildClientForSecurityTokenRequests ( final WSFederationRegisteredService service ) { val cxfBus = BusFactory . getDefaultBus ( ) ; val sts = new SecurityTokenServiceClient ( cxfBus ) ; sts . setAddressingNamespace ( StringUtils . defaultIfBlank ( service . getAddressingNamespace ( ) , WSFederationConstants . HTTP_WWW_W3_ORG_2005_08_ADDRESSING ) ) ; sts . setTokenType ( StringUtils . defaultIfBlank ( service . getTokenType ( ) , WSConstants . WSS_SAML2_TOKEN_TYPE ) ) ; sts . setKeyType ( WSFederationConstants . HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512_BEARER ) ; sts . setWsdlLocation ( prepareWsdlLocation ( service ) ) ; if ( StringUtils . isNotBlank ( service . getPolicyNamespace ( ) ) ) { sts . setWspNamespace ( service . getPolicyNamespace ( ) ) ; } val namespace = StringUtils . defaultIfBlank ( service . getNamespace ( ) , WSFederationConstants . HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512 ) ; sts . setServiceQName ( new QName ( namespace , StringUtils . defaultIfBlank ( service . getWsdlService ( ) , WSFederationConstants . SECURITY_TOKEN_SERVICE ) ) ) ; sts . setEndpointQName ( new QName ( namespace , service . getWsdlEndpoint ( ) ) ) ; sts . getProperties ( ) . putAll ( new HashMap < > ( ) ) ; return sts ; }
Build client for security token requests .
18,023
public SecurityTokenServiceClient buildClientForRelyingPartyTokenResponses ( final SecurityToken securityToken , final WSFederationRegisteredService service ) { val cxfBus = BusFactory . getDefaultBus ( ) ; val sts = new SecurityTokenServiceClient ( cxfBus ) ; sts . setAddressingNamespace ( StringUtils . defaultIfBlank ( service . getAddressingNamespace ( ) , WSFederationConstants . HTTP_WWW_W3_ORG_2005_08_ADDRESSING ) ) ; sts . setWsdlLocation ( prepareWsdlLocation ( service ) ) ; val namespace = StringUtils . defaultIfBlank ( service . getNamespace ( ) , WSFederationConstants . HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512 ) ; sts . setServiceQName ( new QName ( namespace , service . getWsdlService ( ) ) ) ; sts . setEndpointQName ( new QName ( namespace , service . getWsdlEndpoint ( ) ) ) ; sts . setEnableAppliesTo ( StringUtils . isNotBlank ( service . getAppliesTo ( ) ) ) ; sts . setOnBehalfOf ( securityToken . getToken ( ) ) ; sts . setKeyType ( WSFederationConstants . HTTP_DOCS_OASIS_OPEN_ORG_WS_SX_WS_TRUST_200512_BEARER ) ; sts . setTokenType ( StringUtils . defaultIfBlank ( service . getTokenType ( ) , WSConstants . WSS_SAML2_TOKEN_TYPE ) ) ; if ( StringUtils . isNotBlank ( service . getPolicyNamespace ( ) ) ) { sts . setWspNamespace ( service . getPolicyNamespace ( ) ) ; } return sts ; }
Build client for relying party token responses .
18,024
protected Pair < String , String > getClientIdAndClientSecret ( final WebContext context ) { val extractor = new BasicAuthExtractor ( ) ; val upc = extractor . extract ( context ) ; if ( upc != null ) { return Pair . of ( upc . getUsername ( ) , upc . getPassword ( ) ) ; } val clientId = context . getRequestParameter ( OAuth20Constants . CLIENT_ID ) ; val clientSecret = context . getRequestParameter ( OAuth20Constants . CLIENT_SECRET ) ; return Pair . of ( clientId , clientSecret ) ; }
Gets client id and client secret .
18,025
protected Response buildRedirect ( final WebApplicationService service , final Map < String , String > parameters ) { return DefaultResponse . getRedirectResponse ( service . getOriginalUrl ( ) , parameters ) ; }
Build redirect .
18,026
protected Response buildHeader ( final WebApplicationService service , final Map < String , String > parameters ) { return DefaultResponse . getHeaderResponse ( service . getOriginalUrl ( ) , parameters ) ; }
Build header response .
18,027
protected Response buildPost ( final WebApplicationService service , final Map < String , String > parameters ) { return DefaultResponse . getPostResponse ( service . getOriginalUrl ( ) , parameters ) ; }
Build post .
18,028
protected Response . ResponseType getWebApplicationServiceResponseType ( final WebApplicationService finalService ) { val request = HttpRequestUtils . getHttpServletRequestFromRequestAttributes ( ) ; val methodRequest = request != null ? request . getParameter ( CasProtocolConstants . PARAMETER_METHOD ) : null ; final Function < String , String > func = FunctionUtils . doIf ( StringUtils :: isBlank , t -> { val registeredService = this . servicesManager . findServiceBy ( finalService ) ; if ( registeredService != null ) { return registeredService . getResponseType ( ) ; } return null ; } , f -> methodRequest ) ; val method = func . apply ( methodRequest ) ; if ( StringUtils . isBlank ( method ) ) { return Response . ResponseType . REDIRECT ; } return Response . ResponseType . valueOf ( method . toUpperCase ( ) ) ; }
Determine response type response .
18,029
private long findHighestId ( ) { return this . registeredServices . stream ( ) . map ( RegisteredService :: getId ) . max ( Comparator . naturalOrder ( ) ) . orElse ( 0L ) ; }
This isn t super - fast but we don t expect thousands of services .
18,030
@ RequestMapping ( value = ENDPOINT_RESPONSE , method = { RequestMethod . GET , RequestMethod . POST } ) public View redirectResponseToFlow ( @ PathVariable ( "clientName" ) final String clientName , final HttpServletRequest request , final HttpServletResponse response ) { return buildRedirectViewBackToFlow ( clientName , request ) ; }
Redirect response to flow . Receives the CAS OAuth OIDC etc . callback response adjust it to work with the login webflow and redirects the requests to the login webflow endpoint .
18,031
protected View buildRedirectViewBackToFlow ( final String clientName , final HttpServletRequest request ) { val urlBuilder = new URIBuilder ( String . valueOf ( request . getRequestURL ( ) ) ) ; request . getParameterMap ( ) . forEach ( ( k , v ) -> { val value = request . getParameter ( k ) ; urlBuilder . addParameter ( k , value ) ; } ) ; urlBuilder . setPath ( urlBuilder . getPath ( ) . replace ( '/' + clientName , StringUtils . EMPTY ) ) ; urlBuilder . addParameter ( Pac4jConstants . DEFAULT_CLIENT_NAME_PARAMETER , clientName ) ; val url = urlBuilder . toString ( ) ; LOGGER . debug ( "Received a response for client [{}], redirecting the login flow [{}]" , clientName , url ) ; return new RedirectView ( url ) ; }
Build redirect view back to flow view .
18,032
protected View getResultingView ( final IndirectClient < Credentials , CommonProfile > client , final J2EContext webContext , final Ticket ticket ) { val action = client . getRedirectAction ( webContext ) ; if ( RedirectAction . RedirectType . SUCCESS . equals ( action . getType ( ) ) ) { return new DynamicHtmlView ( action . getContent ( ) ) ; } val builder = new URIBuilder ( action . getLocation ( ) ) ; val url = builder . toString ( ) ; LOGGER . debug ( "Redirecting client [{}] to [{}] based on identifier [{}]" , client . getName ( ) , url , ticket . getId ( ) ) ; return new RedirectView ( url ) ; }
Gets resulting view .
18,033
public YubiKeyAccount get ( final String username ) { val result = registry . getAccount ( username ) ; return result . orElse ( null ) ; }
Get yubi key account .
18,034
public static String sha512 ( final String data ) { return digest ( MessageDigestAlgorithms . SHA_512 , data . getBytes ( StandardCharsets . UTF_8 ) ) ; }
Computes hex encoded SHA512 digest .
18,035
public static String sha256 ( final String data ) { return digest ( MessageDigestAlgorithms . SHA_256 , data . getBytes ( StandardCharsets . UTF_8 ) ) ; }
Computes hex encoded SHA256 digest .
18,036
public static String shaBase32 ( final String salt , final String data , final String separator , final boolean chunked ) { val result = rawDigest ( MessageDigestAlgorithms . SHA_1 , salt , separator == null ? data : data + separator ) ; return EncodingUtils . encodeBase32 ( result , chunked ) ; }
Sha base 32 string .
18,037
public static byte [ ] rawDigest ( final String alg , final byte [ ] data ) { try { val digest = getMessageDigestInstance ( alg ) ; return digest . digest ( data ) ; } catch ( final Exception cause ) { throw new SecurityException ( cause ) ; } }
Computes digest .
18,038
public static Response < SearchResult > executeSearchOperation ( final ConnectionFactory connectionFactory , final String baseDn , final SearchFilter filter ) throws LdapException { return executeSearchOperation ( connectionFactory , baseDn , filter , ReturnAttributes . ALL_USER . value ( ) , ReturnAttributes . ALL_USER . value ( ) ) ; }
Execute search operation response .
18,039
public static boolean containsResultEntry ( final Response < SearchResult > response ) { if ( response != null ) { val result = response . getResult ( ) ; return result != null && result . getEntry ( ) != null ; } return false ; }
Checks to see if response has a result .
18,040
public static Connection createConnection ( final ConnectionFactory connectionFactory ) throws LdapException { val c = connectionFactory . getConnection ( ) ; if ( ! c . isOpen ( ) ) { c . open ( ) ; } return c ; }
Gets connection from the factory . Opens the connection if needed .
18,041
public static boolean executePasswordModifyOperation ( final String currentDn , final ConnectionFactory connectionFactory , final String oldPassword , final String newPassword , final AbstractLdapProperties . LdapType type ) { try ( val modifyConnection = createConnection ( connectionFactory ) ) { if ( ! modifyConnection . getConnectionConfig ( ) . getUseSSL ( ) && ! modifyConnection . getConnectionConfig ( ) . getUseStartTLS ( ) ) { LOGGER . warn ( "Executing password modification op under a non-secure LDAP connection; " + "To modify password attributes, the connection to the LDAP server SHOULD be secured and/or encrypted." ) ; } if ( type == AbstractLdapProperties . LdapType . AD ) { LOGGER . debug ( "Executing password modification op for active directory based on " + "[https://support.microsoft.com/en-us/kb/269190]" ) ; val operation = new ModifyOperation ( modifyConnection ) ; val response = operation . execute ( new ModifyRequest ( currentDn , new AttributeModification ( AttributeModificationType . REPLACE , new UnicodePwdAttribute ( newPassword ) ) ) ) ; LOGGER . debug ( "Result code [{}], message: [{}]" , response . getResult ( ) , response . getMessage ( ) ) ; return response . getResultCode ( ) == ResultCode . SUCCESS ; } LOGGER . debug ( "Executing password modification op for generic LDAP" ) ; val operation = new PasswordModifyOperation ( modifyConnection ) ; val response = operation . execute ( new PasswordModifyRequest ( currentDn , StringUtils . isNotBlank ( oldPassword ) ? new Credential ( oldPassword ) : null , new Credential ( newPassword ) ) ) ; LOGGER . debug ( "Result code [{}], message: [{}]" , response . getResult ( ) , response . getMessage ( ) ) ; return response . getResultCode ( ) == ResultCode . SUCCESS ; } catch ( final LdapException e ) { LOGGER . error ( e . getMessage ( ) , e ) ; } return false ; }
Execute a password modify operation .
18,042
public static boolean executeAddOperation ( final ConnectionFactory connectionFactory , final LdapEntry entry ) { try ( val connection = createConnection ( connectionFactory ) ) { val operation = new AddOperation ( connection ) ; operation . execute ( new AddRequest ( entry . getDn ( ) , entry . getAttributes ( ) ) ) ; return true ; } catch ( final LdapException e ) { LOGGER . error ( e . getMessage ( ) , e ) ; } return false ; }
Execute add operation boolean .
18,043
public static boolean executeDeleteOperation ( final ConnectionFactory connectionFactory , final LdapEntry entry ) { try ( val connection = createConnection ( connectionFactory ) ) { val delete = new DeleteOperation ( connection ) ; val request = new DeleteRequest ( entry . getDn ( ) ) ; request . setReferralHandler ( new DeleteReferralHandler ( ) ) ; val res = delete . execute ( request ) ; return res . getResultCode ( ) == ResultCode . SUCCESS ; } catch ( final LdapException e ) { LOGGER . error ( e . getMessage ( ) , e ) ; } return false ; }
Execute delete operation boolean .
18,044
public static SearchRequest newLdaptiveSearchRequest ( final String baseDn , final SearchFilter filter ) { return newLdaptiveSearchRequest ( baseDn , filter , ReturnAttributes . ALL_USER . value ( ) , ReturnAttributes . ALL_USER . value ( ) ) ; }
New ldaptive search request . Returns all attributes .
18,045
public static SearchExecutor newLdaptiveSearchExecutor ( final String baseDn , final String filterQuery , final List < String > params ) { return newLdaptiveSearchExecutor ( baseDn , filterQuery , params , ReturnAttributes . ALL . value ( ) ) ; }
New search executor .
18,046
public static Authenticator newLdaptiveAuthenticator ( final AbstractLdapAuthenticationProperties l ) { switch ( l . getType ( ) ) { case AD : LOGGER . debug ( "Creating active directory authenticator for [{}]" , l . getLdapUrl ( ) ) ; return getActiveDirectoryAuthenticator ( l ) ; case DIRECT : LOGGER . debug ( "Creating direct-bind authenticator for [{}]" , l . getLdapUrl ( ) ) ; return getDirectBindAuthenticator ( l ) ; case AUTHENTICATED : LOGGER . debug ( "Creating authenticated authenticator for [{}]" , l . getLdapUrl ( ) ) ; return getAuthenticatedOrAnonSearchAuthenticator ( l ) ; default : LOGGER . debug ( "Creating anonymous authenticator for [{}]" , l . getLdapUrl ( ) ) ; return getAuthenticatedOrAnonSearchAuthenticator ( l ) ; } }
New ldap authenticator .
18,047
protected static boolean locateMatchingCredentialType ( final Authentication authentication , final String credentialClassType ) { return StringUtils . isNotBlank ( credentialClassType ) && authentication . getCredentials ( ) . stream ( ) . anyMatch ( e -> e . getCredentialClass ( ) . getName ( ) . matches ( credentialClassType ) ) ; }
Locate matching credential type boolean .
18,048
public GitRepositoryBuilder credentialProvider ( final String username , final String password ) { if ( StringUtils . hasText ( username ) ) { this . credentialsProviders . add ( new UsernamePasswordCredentialsProvider ( username , password ) ) ; } return this ; }
Credential provider for repositories that require access .
18,049
public GitRepository build ( ) { try { val providers = this . credentialsProviders . toArray ( CredentialsProvider [ ] :: new ) ; if ( this . repositoryDirectory . exists ( ) ) { val git = Git . open ( this . repositoryDirectory ) ; git . checkout ( ) . setName ( this . activeBranch ) . call ( ) ; return new GitRepository ( git , this . credentialsProviders ) ; } val cloneCommand = Git . cloneRepository ( ) . setProgressMonitor ( new LoggingGitProgressMonitor ( ) ) . setURI ( this . repositoryUri ) . setDirectory ( this . repositoryDirectory ) . setBranch ( this . activeBranch ) . setCredentialsProvider ( new ChainingCredentialsProvider ( providers ) ) ; if ( StringUtils . hasText ( this . branchesToClone ) || "*" . equals ( branchesToClone ) ) { cloneCommand . setCloneAllBranches ( true ) ; } else { cloneCommand . setBranchesToClone ( StringUtils . commaDelimitedListToSet ( this . branchesToClone ) . stream ( ) . map ( GitRepositoryBuilder :: getBranchPath ) . collect ( Collectors . toList ( ) ) ) ; } return new GitRepository ( cloneCommand . call ( ) , credentialsProviders ) ; } catch ( final Exception e ) { throw new IllegalArgumentException ( e . getMessage ( ) , e ) ; } }
Build git repository .
18,050
public static HttpResponse execute ( final String url , final String method , final String basicAuthUsername , final String basicAuthPassword , final Map < String , Object > parameters , final Map < String , Object > headers , final String entity ) { try { val uri = buildHttpUri ( url , parameters ) ; val request = getHttpRequestByMethod ( method . toLowerCase ( ) . trim ( ) , entity , uri ) ; headers . forEach ( ( k , v ) -> request . addHeader ( k , v . toString ( ) ) ) ; prepareHttpRequest ( request , basicAuthUsername , basicAuthPassword , parameters ) ; return HTTP_CLIENT . execute ( request ) ; } catch ( final Exception e ) { LOGGER . error ( e . getMessage ( ) , e ) ; } return null ; }
Execute http request and produce a response .
18,051
public static void close ( final HttpResponse response ) { if ( response instanceof CloseableHttpResponse ) { val closeableHttpResponse = ( CloseableHttpResponse ) response ; try { closeableHttpResponse . close ( ) ; } catch ( final IOException e ) { LOGGER . error ( e . getMessage ( ) , e ) ; } } }
Close the response .
18,052
private static void prepareHttpRequest ( final HttpUriRequest request , final String basicAuthUsername , final String basicAuthPassword , final Map < String , Object > parameters ) { if ( StringUtils . isNotBlank ( basicAuthUsername ) && StringUtils . isNotBlank ( basicAuthPassword ) ) { val auth = EncodingUtils . encodeBase64 ( basicAuthUsername + ':' + basicAuthPassword ) ; request . setHeader ( HttpHeaders . AUTHORIZATION , "Basic " + auth ) ; } }
Prepare http request . Tries to set the authorization header in cases where the URL endpoint does not actually produce the header on its own .
18,053
public static org . springframework . http . HttpHeaders createBasicAuthHeaders ( final String basicAuthUser , final String basicAuthPassword ) { val acceptHeaders = new org . springframework . http . HttpHeaders ( ) ; acceptHeaders . setAccept ( CollectionUtils . wrap ( MediaType . APPLICATION_JSON ) ) ; if ( StringUtils . isNotBlank ( basicAuthUser ) && StringUtils . isNotBlank ( basicAuthPassword ) ) { val authorization = basicAuthUser + ':' + basicAuthPassword ; val basic = EncodingUtils . encodeBase64 ( authorization . getBytes ( Charset . forName ( "US-ASCII" ) ) ) ; acceptHeaders . set ( org . springframework . http . HttpHeaders . AUTHORIZATION , "Basic " + basic ) ; } return acceptHeaders ; }
Create headers org . springframework . http . http headers .
18,054
protected String buildAndEncodeConsentAttributes ( final Map < String , List < Object > > attributes ) { try { val json = MAPPER . writer ( new MinimalPrettyPrinter ( ) ) . writeValueAsString ( attributes ) ; val base64 = EncodingUtils . encodeBase64 ( json ) ; return this . consentCipherExecutor . encode ( base64 ) ; } catch ( final Exception e ) { throw new IllegalArgumentException ( "Could not serialize attributes for consent decision" ) ; } }
Build consent attribute names string .
18,055
private void removeSessionTicket ( final String id ) { val ticketId = TransientSessionTicketFactory . normalizeTicketId ( id ) ; this . ticketRegistry . deleteTicket ( ticketId ) ; }
Remove session ticket .
18,056
@ GetMapping ( value = "/v1/tickets/{id:.+}" ) public ResponseEntity < String > getTicketStatus ( @ PathVariable ( "id" ) final String id ) { try { val ticket = this . centralAuthenticationService . getTicket ( id ) ; return new ResponseEntity < > ( ticket . getId ( ) , HttpStatus . OK ) ; } catch ( final InvalidTicketException e ) { return new ResponseEntity < > ( "Ticket could not be found" , HttpStatus . NOT_FOUND ) ; } catch ( final Exception e ) { LOGGER . error ( e . getMessage ( ) , e ) ; return new ResponseEntity < > ( e . getMessage ( ) , HttpStatus . INTERNAL_SERVER_ERROR ) ; } }
Determine the status of a given ticket id whether it s valid exists expired etc .
18,057
protected Map < String , Object > decryptProperties ( final Map properties ) { return configurationCipherExecutor . decode ( properties , ArrayUtils . EMPTY_OBJECT_ARRAY ) ; }
Decrypt properties map .
18,058
protected String digestEncodedPassword ( final String encodedPassword , final Map < String , Object > values ) { val hashService = new DefaultHashService ( ) ; if ( StringUtils . isNotBlank ( this . staticSalt ) ) { hashService . setPrivateSalt ( ByteSource . Util . bytes ( this . staticSalt ) ) ; } hashService . setHashAlgorithmName ( this . algorithmName ) ; if ( values . containsKey ( this . numberOfIterationsFieldName ) ) { val longAsStr = values . get ( this . numberOfIterationsFieldName ) . toString ( ) ; hashService . setHashIterations ( Integer . parseInt ( longAsStr ) ) ; } else { hashService . setHashIterations ( this . numberOfIterations ) ; } if ( ! values . containsKey ( this . saltFieldName ) ) { throw new IllegalArgumentException ( "Specified field name for salt does not exist in the results" ) ; } val dynaSalt = values . get ( this . saltFieldName ) . toString ( ) ; val request = new HashRequest . Builder ( ) . setSalt ( dynaSalt ) . setSource ( encodedPassword ) . build ( ) ; return hashService . computeHash ( request ) . toHex ( ) ; }
Digest encoded password .
18,059
static void ensurePrincipalAccessIsAllowedForService ( final Service service , final RegisteredService registeredService , final TicketGrantingTicket ticketGrantingTicket , final boolean retrievePrincipalAttributesFromReleasePolicy ) throws UnauthorizedServiceException , PrincipalException { ensurePrincipalAccessIsAllowedForService ( service , registeredService , ticketGrantingTicket . getRoot ( ) . getAuthentication ( ) , retrievePrincipalAttributesFromReleasePolicy ) ; }
Ensure service access is allowed . Determines the final authentication object by looking into the chained authentications of the ticket granting ticket .
18,060
public static Predicate < RegisteredService > getRegisteredServiceExpirationPolicyPredicate ( ) { return service -> { try { if ( service == null ) { return false ; } val policy = service . getExpirationPolicy ( ) ; if ( policy == null || StringUtils . isBlank ( policy . getExpirationDate ( ) ) ) { return true ; } val now = getCurrentSystemTime ( ) ; val expirationDate = DateTimeUtils . localDateTimeOf ( policy . getExpirationDate ( ) ) ; LOGGER . debug ( "Service expiration date is [{}] while now is [{}]" , expirationDate , now ) ; return ! now . isAfter ( expirationDate ) ; } catch ( final Exception e ) { LOGGER . warn ( e . getMessage ( ) , e ) ; } return false ; } ; }
Returns a predicate that determined whether a service has expired .
18,061
@ ReadOperation ( produces = MediaType . APPLICATION_JSON_VALUE ) public Map < ? , ? > fetchAccountStatus ( final String username , final String providerId ) { val results = new LinkedHashMap < > ( ) ; val providers = applicationContext . getBeansOfType ( DuoMultifactorAuthenticationProvider . class ) . values ( ) ; providers . stream ( ) . filter ( Objects :: nonNull ) . map ( DuoMultifactorAuthenticationProvider . class :: cast ) . filter ( provider -> StringUtils . isBlank ( providerId ) || provider . matches ( providerId ) ) . forEach ( p -> { val duoService = p . getDuoAuthenticationService ( ) ; val accountStatus = duoService . getDuoUserAccount ( username ) ; results . put ( p . getId ( ) , CollectionUtils . wrap ( "duoApiHost" , duoService . getApiHost ( ) , "name" , p . getFriendlyName ( ) , "accountStatus" , accountStatus ) ) ; } ) ; return results ; }
Fetch account status map .
18,062
private String getPasswordOnRecord ( final String username ) throws IOException { try ( val stream = Files . lines ( fileName . getFile ( ) . toPath ( ) ) ) { return stream . map ( line -> line . split ( this . separator ) ) . filter ( lineFields -> { val userOnRecord = lineFields [ 0 ] ; return username . equals ( userOnRecord ) ; } ) . map ( lineFields -> lineFields [ 1 ] ) . findFirst ( ) . orElse ( null ) ; } }
Gets the password on record .
18,063
@ GetMapping ( path = "/yadis.xml" ) public void yadis ( final HttpServletResponse response ) throws Exception { val template = this . resourceLoader . getResource ( "classpath:/yadis.template" ) ; try ( val writer = new StringWriter ( ) ) { IOUtils . copy ( template . getInputStream ( ) , writer , StandardCharsets . UTF_8 ) ; val yadis = writer . toString ( ) . replace ( "$casLoginUrl" , casProperties . getServer ( ) . getLoginUrl ( ) ) ; response . setContentType ( "application/xrds+xml" ) ; val respWriter = response . getWriter ( ) ; respWriter . write ( yadis ) ; respWriter . flush ( ) ; } }
Generates the Yadis XML snippet .
18,064
public void publishEvent ( final ApplicationEvent event ) { if ( this . eventPublisher != null ) { LOGGER . trace ( "Publishing event [{}]" , event ) ; this . eventPublisher . publishEvent ( event ) ; } }
Publish event .
18,065
private void handleEvent ( final WatchKey key ) { try { key . pollEvents ( ) . forEach ( event -> { val eventName = event . kind ( ) . name ( ) ; val ev = ( WatchEvent < Path > ) event ; val filename = ev . context ( ) ; val parent = ( Path ) key . watchable ( ) ; val fullPath = parent . resolve ( filename ) ; val file = fullPath . toFile ( ) ; LOGGER . trace ( "Detected event [{}] on file [{}]" , eventName , file ) ; if ( eventName . equals ( ENTRY_CREATE . name ( ) ) && file . exists ( ) ) { onCreate . accept ( file ) ; } else if ( eventName . equals ( ENTRY_DELETE . name ( ) ) ) { onDelete . accept ( file ) ; } else if ( eventName . equals ( ENTRY_MODIFY . name ( ) ) && file . exists ( ) ) { onModify . accept ( file ) ; } } ) ; } catch ( final Exception e ) { LOGGER . warn ( e . getMessage ( ) , e ) ; } }
Handle event .
18,066
public void start ( final String name ) { thread = new Thread ( this ) ; thread . setName ( name ) ; thread . start ( ) ; }
Start thread .
18,067
public void handleCasTicketGrantingTicketCreatedEvent ( final CasTicketGrantingTicketCreatedEvent event ) { if ( this . casEventRepository != null ) { val dto = prepareCasEvent ( event ) ; dto . setCreationTime ( event . getTicketGrantingTicket ( ) . getCreationTime ( ) . toString ( ) ) ; dto . putEventId ( TicketIdSanitizationUtils . sanitize ( event . getTicketGrantingTicket ( ) . getId ( ) ) ) ; dto . setPrincipalId ( event . getTicketGrantingTicket ( ) . getAuthentication ( ) . getPrincipal ( ) . getId ( ) ) ; this . casEventRepository . save ( dto ) ; } }
Handle TGT creation event .
18,068
public void handleCasRiskyAuthenticationDetectedEvent ( final CasRiskyAuthenticationDetectedEvent event ) { if ( this . casEventRepository != null ) { val dto = prepareCasEvent ( event ) ; dto . putEventId ( event . getService ( ) . getName ( ) ) ; dto . setPrincipalId ( event . getAuthentication ( ) . getPrincipal ( ) . getId ( ) ) ; this . casEventRepository . save ( dto ) ; } }
Handle cas risky authentication detected event .
18,069
public static InetAddress getByName ( final String urlAddr ) { try { val url = new URL ( urlAddr ) ; return InetAddress . getByName ( url . getHost ( ) ) ; } catch ( final Exception e ) { LOGGER . trace ( "Host name could not be determined automatically." , e ) ; } return null ; }
Gets by name .
18,070
public static String getCasServerHostName ( ) { val hostName = InetAddress . getLocalHost ( ) . getHostName ( ) ; val index = hostName . indexOf ( '.' ) ; if ( index > 0 ) { return hostName . substring ( 0 , index ) ; } return hostName ; }
Gets cas server host name .
18,071
public static String getCasServerHostAddress ( final String name ) { val host = getByName ( name ) ; if ( host != null ) { return host . getHostAddress ( ) ; } return null ; }
Gets cas server host address .
18,072
public Set < ? extends MultifactorAuthenticationTrustRecord > devices ( ) { val onOrAfter = expireRecordsByDate ( ) ; return this . mfaTrustEngine . get ( onOrAfter ) ; }
Devices registered and trusted .
18,073
public Set < ? extends MultifactorAuthenticationTrustRecord > devicesForUser ( final String username ) { val onOrAfter = expireRecordsByDate ( ) ; return this . mfaTrustEngine . get ( username , onOrAfter ) ; }
Devices for user .
18,074
public Integer revoke ( final String key ) { this . mfaTrustEngine . expire ( key ) ; return HttpStatus . OK . value ( ) ; }
Revoke record and return status .
18,075
public void put ( final String key , final String value ) { if ( StringUtils . isBlank ( value ) ) { this . properties . remove ( key ) ; } else { this . properties . put ( key , value ) ; } }
Put property .
18,076
public void putGeoLocation ( final GeoLocationRequest location ) { putGeoAccuracy ( location . getAccuracy ( ) ) ; putGeoLatitude ( location . getLatitude ( ) ) ; putGeoLongitude ( location . getLongitude ( ) ) ; putGeoTimestamp ( location . getTimestamp ( ) ) ; }
Put geo location .
18,077
public GeoLocationRequest getGeoLocation ( ) { val request = new GeoLocationRequest ( ) ; request . setAccuracy ( get ( "geoAccuracy" ) ) ; request . setTimestamp ( get ( "geoTimestamp" ) ) ; request . setLongitude ( get ( "geoLongitude" ) ) ; request . setLatitude ( get ( "geoLatitude" ) ) ; return request ; }
Gets geo location .
18,078
protected void updateTicketGrantingTicketState ( ) { val ticketGrantingTicket = getTicketGrantingTicket ( ) ; if ( ticketGrantingTicket != null && ! ticketGrantingTicket . isExpired ( ) ) { val state = TicketState . class . cast ( ticketGrantingTicket ) ; state . update ( ) ; } }
Update ticket granting ticket state .
18,079
protected void updateTicketState ( ) { LOGGER . trace ( "Before updating ticket [{}]\n\tPrevious time used: [{}]\n\tLast time used: [{}]\n\tUsage count: [{}]" , getId ( ) , this . previousTimeUsed , this . lastTimeUsed , this . countOfUses ) ; this . previousTimeUsed = ZonedDateTime . from ( this . lastTimeUsed ) ; this . lastTimeUsed = ZonedDateTime . now ( ZoneOffset . UTC ) ; this . countOfUses ++ ; LOGGER . trace ( "After updating ticket [{}]\n\tPrevious time used: [{}]\n\tLast time used: [{}]\n\tUsage count: [{}]" , getId ( ) , this . previousTimeUsed , this . lastTimeUsed , this . countOfUses ) ; }
Update ticket state .
18,080
private Event submit ( final RequestContext context , final Credential credential , final MessageContext messageContext ) { if ( repository . submit ( context , credential ) ) { return new EventFactorySupport ( ) . event ( this , CasWebflowConstants . TRANSITION_ID_AUP_ACCEPTED ) ; } return error ( ) ; }
Record the fact that the policy is accepted .
18,081
private static String getUPNStringFromSequence ( final ASN1Sequence seq ) { if ( seq == null ) { return null ; } val id = ASN1ObjectIdentifier . getInstance ( seq . getObjectAt ( 0 ) ) ; if ( id != null && UPN_OBJECTID . equals ( id . getId ( ) ) ) { val obj = ( ASN1TaggedObject ) seq . getObjectAt ( 1 ) ; val primitiveObj = obj . getObject ( ) ; val func = FunctionUtils . doIf ( Predicates . instanceOf ( ASN1TaggedObject . class ) , ( ) -> ASN1TaggedObject . getInstance ( primitiveObj ) . getObject ( ) , ( ) -> primitiveObj ) ; val prim = func . apply ( primitiveObj ) ; if ( prim instanceof ASN1OctetString ) { return new String ( ( ( ASN1OctetString ) prim ) . getOctets ( ) , StandardCharsets . UTF_8 ) ; } if ( prim instanceof ASN1String ) { return ( ( ASN1String ) prim ) . getString ( ) ; } } return null ; }
Get UPN String .
18,082
@ View ( name = "by_username" , map = "function(doc) { if(doc.secretKey) { emit(doc.username, doc) } }" ) public CouchDbGoogleAuthenticatorAccount findOneByUsername ( final String username ) { val view = createQuery ( "by_username" ) . key ( username ) . limit ( 1 ) ; try { return db . queryView ( view , CouchDbGoogleAuthenticatorAccount . class ) . stream ( ) . findFirst ( ) . orElse ( null ) ; } catch ( final DocumentNotFoundException ignored ) { return null ; } }
Find first account for user .
18,083
public List < CouchDbGoogleAuthenticatorAccount > findByUsername ( final String username ) { try { return queryView ( "by_username" , username ) ; } catch ( final DocumentNotFoundException ignored ) { return null ; } }
Final all accounts for user .
18,084
@ UpdateHandler ( name = "delete_token_account" , file = "CouchDbOneTimeTokenAccount_delete.js" ) public void deleteTokenAccount ( final CouchDbGoogleAuthenticatorAccount token ) { db . callUpdateHandler ( stdDesignDocumentId , "delete_token_account" , token . getCid ( ) , null ) ; }
Delete token without revision checks .
18,085
@ View ( name = "count" , map = "function(doc) { if(doc.secretKey) { emit(doc._id, doc) } }" , reduce = "_count" ) public long count ( ) { return db . queryView ( createQuery ( "count" ) ) . getRows ( ) . get ( 0 ) . getValueAsInt ( ) ; }
Total token accounts in database .
18,086
public static Optional < Object > firstElement ( final Object obj ) { val object = CollectionUtils . toCollection ( obj ) ; if ( object . isEmpty ( ) ) { return Optional . empty ( ) ; } return Optional . of ( object . iterator ( ) . next ( ) ) ; }
Converts the provided object into a collection and return the first element or empty .
18,087
public static < T extends Collection > T toCollection ( final Object obj , final Class < T > clazz ) { val results = toCollection ( obj ) ; if ( clazz . isInterface ( ) ) { throw new IllegalArgumentException ( "Cannot accept an interface " + clazz . getSimpleName ( ) + " to create a new object instance" ) ; } val col = clazz . getDeclaredConstructor ( ) . newInstance ( ) ; col . addAll ( results ) ; return col ; }
To collection t .
18,088
public static < K , V > Map < K , V > wrap ( final Map < K , V > source ) { if ( source != null && ! source . isEmpty ( ) ) { return new HashMap < > ( source ) ; } return new HashMap < > ( 0 ) ; }
Wraps a possibly null map in an immutable wrapper .
18,089
public static < T > Set < T > wrap ( final Set < T > source ) { val list = new LinkedHashSet < T > ( ) ; if ( source != null && ! source . isEmpty ( ) ) { list . addAll ( source ) ; } return list ; }
Wrap varargs .
18,090
public static < T > Set < T > wrapSet ( final T ... source ) { val list = new LinkedHashSet < T > ( ) ; addToCollection ( list , source ) ; return list ; }
Wrap set .
18,091
public static Map < String , String > convertDirectedListToMap ( final List < String > inputList ) { val mappings = new TreeMap < String , String > ( ) ; inputList . stream ( ) . map ( s -> { val bits = Splitter . on ( "->" ) . splitToList ( s ) ; return Pair . of ( bits . get ( 0 ) , bits . get ( 1 ) ) ; } ) . forEach ( p -> mappings . put ( p . getKey ( ) , p . getValue ( ) ) ) ; return mappings ; }
Convert directed list to map .
18,092
protected Set < Event > resolveMultifactorAuthenticationProvider ( final Optional < RequestContext > context , final RegisteredService service , final Principal principal ) { val globalPrincipalAttributeValueRegex = casProperties . getAuthn ( ) . getMfa ( ) . getGlobalPrincipalAttributeValueRegex ( ) ; val providerMap = MultifactorAuthenticationUtils . getAvailableMultifactorAuthenticationProviders ( ApplicationContextProvider . getApplicationContext ( ) ) ; val providers = providerMap . values ( ) ; if ( providers . size ( ) == 1 && StringUtils . isNotBlank ( globalPrincipalAttributeValueRegex ) ) { return resolveSingleMultifactorProvider ( context , service , principal , providers ) ; } return resolveMultifactorProviderViaPredicate ( context , service , principal , providers ) ; }
Resolve multifactor authentication provider set .
18,093
protected Set < Event > resolveMultifactorProviderViaPredicate ( final Optional < RequestContext > context , final RegisteredService service , final Principal principal , final Collection < MultifactorAuthenticationProvider > providers ) { val attributeNames = commaDelimitedListToSet ( casProperties . getAuthn ( ) . getMfa ( ) . getGlobalPrincipalAttributeNameTriggers ( ) ) ; return multifactorAuthenticationProviderResolver . resolveEventViaPrincipalAttribute ( principal , attributeNames , service , context , providers , input -> providers . stream ( ) . anyMatch ( provider -> input != null && provider . matches ( input ) ) ) ; }
Resolve multifactor provider by regex predicate set .
18,094
protected Set < Event > resolveSingleMultifactorProvider ( final Optional < RequestContext > context , final RegisteredService service , final Principal principal , final Collection < MultifactorAuthenticationProvider > providers ) { val globalPrincipalAttributeValueRegex = casProperties . getAuthn ( ) . getMfa ( ) . getGlobalPrincipalAttributeValueRegex ( ) ; val provider = providers . iterator ( ) . next ( ) ; LOGGER . trace ( "Found a single multifactor provider [{}] in the application context" , provider ) ; val attributeNames = commaDelimitedListToSet ( casProperties . getAuthn ( ) . getMfa ( ) . getGlobalPrincipalAttributeNameTriggers ( ) ) ; return multifactorAuthenticationProviderResolver . resolveEventViaPrincipalAttribute ( principal , attributeNames , service , context , providers , input -> input != null && input . matches ( globalPrincipalAttributeValueRegex ) ) ; }
Resolve single multifactor provider set .
18,095
protected void encodeAndEncryptCredentialPassword ( final Map < String , Object > attributes , final Map < String , String > cachedAttributesToEncode , final RegisteredServiceCipherExecutor cipher , final RegisteredService registeredService ) { if ( cachedAttributesToEncode . containsKey ( CasViewConstants . MODEL_ATTRIBUTE_NAME_PRINCIPAL_CREDENTIAL ) ) { val value = cachedAttributesToEncode . get ( CasViewConstants . MODEL_ATTRIBUTE_NAME_PRINCIPAL_CREDENTIAL ) ; val decodedValue = this . cacheCredentialCipherExecutor . decode ( value , ArrayUtils . EMPTY_OBJECT_ARRAY ) ; cachedAttributesToEncode . remove ( CasViewConstants . MODEL_ATTRIBUTE_NAME_PRINCIPAL_CREDENTIAL ) ; if ( StringUtils . isNotBlank ( decodedValue ) ) { cachedAttributesToEncode . put ( CasViewConstants . MODEL_ATTRIBUTE_NAME_PRINCIPAL_CREDENTIAL , decodedValue ) ; } } encryptAndEncodeAndPutIntoAttributesMap ( attributes , cachedAttributesToEncode , CasViewConstants . MODEL_ATTRIBUTE_NAME_PRINCIPAL_CREDENTIAL , cipher , registeredService ) ; }
Encode and encrypt credential password using the public key supplied by the service . The result is base64 encoded and put into the attributes collection again overwriting the previous value .
18,096
protected void encodeAndEncryptProxyGrantingTicket ( final Map < String , Object > attributes , final Map < String , String > cachedAttributesToEncode , final RegisteredServiceCipherExecutor cipher , final RegisteredService registeredService ) { encryptAndEncodeAndPutIntoAttributesMap ( attributes , cachedAttributesToEncode , CasViewConstants . MODEL_ATTRIBUTE_NAME_PROXY_GRANTING_TICKET , cipher , registeredService ) ; encryptAndEncodeAndPutIntoAttributesMap ( attributes , cachedAttributesToEncode , CasViewConstants . MODEL_ATTRIBUTE_NAME_PROXY_GRANTING_TICKET_IOU , cipher , registeredService ) ; }
Encode and encrypt pgt .
18,097
protected void encryptAndEncodeAndPutIntoAttributesMap ( final Map < String , Object > attributes , final Map < String , String > cachedAttributesToEncode , final String cachedAttributeName , final RegisteredServiceCipherExecutor cipher , final RegisteredService registeredService ) { val cachedAttribute = cachedAttributesToEncode . remove ( cachedAttributeName ) ; if ( StringUtils . isNotBlank ( cachedAttribute ) ) { LOGGER . trace ( "Retrieved [{}] as a cached model attribute..." , cachedAttributeName ) ; val encodedValue = cipher . encode ( cachedAttribute , Optional . of ( registeredService ) ) ; if ( StringUtils . isNotBlank ( encodedValue ) ) { attributes . put ( cachedAttributeName , encodedValue ) ; LOGGER . trace ( "Encrypted and encoded [{}] as an attribute to [{}]." , cachedAttributeName , encodedValue ) ; } else { LOGGER . warn ( "Attribute [{}] cannot be encoded and is removed from the collection of attributes" , cachedAttributeName ) ; } } else { LOGGER . trace ( "[{}] is not available as a cached model attribute to encrypt..." , cachedAttributeName ) ; } }
Encrypt encode and put the attribute into attributes map .
18,098
protected AccessTokenRequestDataHolder extractInternal ( final HttpServletRequest request , final HttpServletResponse response , final AccessTokenRequestDataHolder . AccessTokenRequestDataHolderBuilder builder ) { return builder . build ( ) ; }
Extract internal access token request .
18,099
protected OAuthToken getOAuthTokenFromRequest ( final HttpServletRequest request ) { val token = getOAuthConfigurationContext ( ) . getTicketRegistry ( ) . getTicket ( getOAuthParameter ( request ) , OAuthToken . class ) ; if ( token == null || token . isExpired ( ) ) { LOGGER . error ( "OAuth token indicated by parameter [{}] has expired or not found: [{}]" , getOAuthParameter ( request ) , token ) ; if ( token != null ) { getOAuthConfigurationContext ( ) . getTicketRegistry ( ) . deleteTicket ( token . getId ( ) ) ; } return null ; } return token ; }
Return the OAuth token .