idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
17,700
public static Credential getCredential ( final RequestContext context ) { val cFromRequest = ( Credential ) context . getRequestScope ( ) . get ( PARAMETER_CREDENTIAL ) ; val cFromFlow = ( Credential ) context . getFlowScope ( ) . get ( PARAMETER_CREDENTIAL ) ; val cFromConversation = ( Credential ) context . getConversationScope ( ) . get ( PARAMETER_CREDENTIAL ) ; var credential = cFromRequest ; if ( credential == null || StringUtils . isBlank ( credential . getId ( ) ) ) { credential = cFromFlow ; } if ( credential == null || StringUtils . isBlank ( credential . getId ( ) ) ) { credential = cFromConversation ; if ( credential != null && ! StringUtils . isBlank ( credential . getId ( ) ) ) { context . getFlowScope ( ) . put ( PARAMETER_CREDENTIAL , credential ) ; } } if ( credential == null ) { val session = context . getFlowExecutionContext ( ) . getActiveSession ( ) ; credential = session . getScope ( ) . get ( PARAMETER_CREDENTIAL , Credential . class ) ; } if ( credential != null && StringUtils . isBlank ( credential . getId ( ) ) ) { return null ; } return credential ; }
Gets credential from the context .
17,701
public static void putCredential ( final RequestContext context , final Credential c ) { if ( c == null ) { context . getRequestScope ( ) . remove ( PARAMETER_CREDENTIAL ) ; context . getFlowScope ( ) . remove ( PARAMETER_CREDENTIAL ) ; context . getConversationScope ( ) . remove ( PARAMETER_CREDENTIAL ) ; } else { context . getRequestScope ( ) . put ( PARAMETER_CREDENTIAL , c ) ; context . getFlowScope ( ) . put ( PARAMETER_CREDENTIAL , c ) ; context . getConversationScope ( ) . put ( PARAMETER_CREDENTIAL , c ) ; } }
Puts credential into the context .
17,702
public static boolean isAuthenticatingAtPublicWorkstation ( final RequestContext ctx ) { if ( ctx . getFlowScope ( ) . contains ( PUBLIC_WORKSTATION_ATTRIBUTE ) ) { LOGGER . debug ( "Public workstation flag detected. SSO session will be considered renewed." ) ; return true ; } return false ; }
Is authenticating at a public workstation?
17,703
public static void putPublicWorkstationToFlowIfRequestParameterPresent ( final RequestContext context ) { if ( StringUtils . isNotBlank ( context . getExternalContext ( ) . getRequestParameterMap ( ) . get ( PUBLIC_WORKSTATION_ATTRIBUTE ) ) ) { context . getFlowScope ( ) . put ( PUBLIC_WORKSTATION_ATTRIBUTE , Boolean . TRUE ) ; } }
Put public workstation into the flow if request parameter present .
17,704
public static void putWarnCookieIfRequestParameterPresent ( final CasCookieBuilder warnCookieGenerator , final RequestContext context ) { if ( warnCookieGenerator != null ) { LOGGER . trace ( "Evaluating request to determine if warning cookie should be generated" ) ; val response = WebUtils . getHttpServletResponseFromExternalWebflowContext ( context ) ; if ( StringUtils . isNotBlank ( context . getExternalContext ( ) . getRequestParameterMap ( ) . get ( "warn" ) ) ) { warnCookieGenerator . addCookie ( response , "true" ) ; } } else { LOGGER . trace ( "No warning cookie generator is defined" ) ; } }
Put warn cookie if request parameter present .
17,705
public static void putAuthentication ( final Authentication authentication , final RequestContext ctx ) { ctx . getConversationScope ( ) . put ( PARAMETER_AUTHENTICATION , authentication ) ; }
Put authentication into conversation scope .
17,706
public static void putAuthenticationResultBuilder ( final AuthenticationResultBuilder builder , final RequestContext ctx ) { ctx . getConversationScope ( ) . put ( PARAMETER_AUTHENTICATION_RESULT_BUILDER , builder ) ; }
Put authentication result builder .
17,707
public static Principal getPrincipalFromRequestContext ( final RequestContext requestContext , final TicketRegistrySupport ticketRegistrySupport ) { val tgt = WebUtils . getTicketGrantingTicketId ( requestContext ) ; if ( StringUtils . isBlank ( tgt ) ) { throw new IllegalArgumentException ( "No ticket-granting ticket could be found in the context" ) ; } return ticketRegistrySupport . getAuthenticatedPrincipalFrom ( tgt ) ; }
Gets the authenticated principal .
17,708
public static void putAuthenticationResult ( final AuthenticationResult authenticationResult , final RequestContext context ) { context . getConversationScope ( ) . put ( PARAMETER_AUTHENTICATION_RESULT , authenticationResult ) ; }
Put authentication result .
17,709
public static String getHttpServletRequestUserAgentFromRequestContext ( final RequestContext context ) { val request = getHttpServletRequestFromExternalWebflowContext ( context ) ; return getHttpServletRequestUserAgentFromRequestContext ( request ) ; }
Gets http servlet request user agent from request context .
17,710
public static GeoLocationRequest getHttpServletRequestGeoLocationFromRequestContext ( final RequestContext context ) { val servletRequest = getHttpServletRequestFromExternalWebflowContext ( context ) ; return getHttpServletRequestGeoLocation ( servletRequest ) ; }
Gets http servlet request geo location from request context .
17,711
public static void putRecaptchaPropertiesFlowScope ( final RequestContext context , final GoogleRecaptchaProperties googleRecaptcha ) { val flowScope = context . getFlowScope ( ) ; flowScope . put ( "recaptchaSiteKey" , googleRecaptcha . getSiteKey ( ) ) ; flowScope . put ( "recaptchaInvisible" , googleRecaptcha . isInvisible ( ) ) ; flowScope . put ( "recaptchaPosition" , googleRecaptcha . getPosition ( ) ) ; flowScope . put ( "recaptchaVersion" , googleRecaptcha . getVersion ( ) . name ( ) . toLowerCase ( ) ) ; }
Put recaptcha settings flow scope .
17,712
public static void putResolvedMultifactorAuthenticationProviders ( final RequestContext context , final Collection < MultifactorAuthenticationProvider > value ) { val providerIds = value . stream ( ) . map ( MultifactorAuthenticationProvider :: getId ) . collect ( Collectors . toSet ( ) ) ; context . getConversationScope ( ) . put ( "resolvedMultifactorAuthenticationProviders" , providerIds ) ; }
Put resolved multifactor authentication providers into scope .
17,713
public static void putServiceUserInterfaceMetadata ( final RequestContext requestContext , final Serializable mdui ) { if ( mdui != null ) { requestContext . getFlowScope ( ) . put ( PARAMETER_SERVICE_UI_METADATA , mdui ) ; } }
Sets service user interface metadata .
17,714
public static < T > T getServiceUserInterfaceMetadata ( final RequestContext requestContext , final Class < T > clz ) { if ( requestContext . getFlowScope ( ) . contains ( PARAMETER_SERVICE_UI_METADATA ) ) { return requestContext . getFlowScope ( ) . get ( PARAMETER_SERVICE_UI_METADATA , clz ) ; } return null ; }
Gets service user interface metadata .
17,715
public static void putServiceResponseIntoRequestScope ( final RequestContext requestContext , final Response response ) { requestContext . getRequestScope ( ) . put ( "parameters" , response . getAttributes ( ) ) ; putServiceRedirectUrl ( requestContext , response . getUrl ( ) ) ; }
Put service response into request scope .
17,716
public static void putServiceOriginalUrlIntoRequestScope ( final RequestContext requestContext , final WebApplicationService service ) { requestContext . getRequestScope ( ) . put ( "originalUrl" , service . getOriginalUrl ( ) ) ; }
Put service original url into request scope .
17,717
public static Authentication getInProgressAuthentication ( ) { val context = RequestContextHolder . getRequestContext ( ) ; val authentication = context != null ? WebUtils . getAuthentication ( context ) : null ; if ( authentication == null ) { return AuthenticationCredentialsThreadLocalBinder . getInProgressAuthentication ( ) ; } return authentication ; }
Gets in progress authentication .
17,718
public static void putSurrogateAuthenticationAccounts ( final RequestContext requestContext , final List < String > surrogates ) { requestContext . getFlowScope ( ) . put ( "surrogates" , surrogates ) ; }
Put surrogate authentication accounts .
17,719
public static void putAvailableAuthenticationHandleNames ( final RequestContext context , final Collection < String > availableHandlers ) { context . getFlowScope ( ) . put ( "availableAuthenticationHandlerNames" , availableHandlers ) ; }
Put available authentication handle names .
17,720
public static void putInitialHttpRequestPostParameters ( final RequestContext context ) { val request = getHttpServletRequestFromExternalWebflowContext ( context ) ; context . getFlashScope ( ) . put ( "httpRequestInitialPostParameters" , request . getParameterMap ( ) ) ; }
Put initial http request post parameters .
17,721
@ SuppressWarnings ( "FutureReturnValueIgnored" ) public void init ( ) { if ( ! validateConfiguration ( ) ) { return ; } val results = this . fetcher . fetch ( getResources ( ) ) ; ResourceCRLRevocationChecker . this . addCrls ( results ) ; final Runnable scheduledFetcher = ( ) -> { try { val fetchedResults = getFetcher ( ) . fetch ( getResources ( ) ) ; ResourceCRLRevocationChecker . this . addCrls ( fetchedResults ) ; } catch ( final Exception e ) { LOGGER . debug ( e . getMessage ( ) , e ) ; } } ; this . scheduler . scheduleAtFixedRate ( scheduledFetcher , this . refreshInterval , this . refreshInterval , TimeUnit . SECONDS ) ; }
Initializes the process that periodically fetches CRL data .
17,722
private void addCrls ( final Collection < X509CRL > results ) { results . forEach ( entry -> addCRL ( entry . getIssuerX500Principal ( ) , entry ) ) ; }
Add fetched crls to the map .
17,723
public boolean isEligibleForContextRefresh ( ) { if ( this . override ) { return true ; } if ( getFile ( ) != null ) { return CONFIG_FILE_PATTERN . matcher ( getFile ( ) . toFile ( ) . getName ( ) ) . find ( ) ; } return false ; }
Is eligible for context refresh ?
17,724
protected String getAuthenticationContextByAssertion ( final Object assertion , final RequestedAuthnContext requestedAuthnContext , final List < AuthnContextClassRef > authnContextClassRefs ) { LOGGER . debug ( "AuthN Context comparison is requested to use [{}]" , requestedAuthnContext . getComparison ( ) ) ; authnContextClassRefs . forEach ( c -> LOGGER . debug ( "Requested AuthN Context [{}]" , c . getAuthnContextClassRef ( ) ) ) ; return null ; }
Gets authentication context by assertion . This is more of a template method for the time being and may be enhanced later to support more advanced parsing of classes from the assertion .
17,725
public void createServicesTable ( final boolean deleteTables ) { LOGGER . debug ( "Attempting to create DynamoDb services table" ) ; val request = new CreateTableRequest ( ) . withAttributeDefinitions ( new AttributeDefinition ( ColumnNames . ID . getColumnName ( ) , ScalarAttributeType . S ) ) . withKeySchema ( new KeySchemaElement ( ColumnNames . ID . getColumnName ( ) , KeyType . HASH ) ) . withProvisionedThroughput ( new ProvisionedThroughput ( dynamoDbProperties . getReadCapacity ( ) , dynamoDbProperties . getWriteCapacity ( ) ) ) . withTableName ( dynamoDbProperties . getTableName ( ) ) ; if ( deleteTables ) { val delete = new DeleteTableRequest ( request . getTableName ( ) ) ; LOGGER . debug ( "Sending delete request [{}] to remove table if necessary" , delete ) ; TableUtils . deleteTableIfExists ( amazonDynamoDBClient , delete ) ; } LOGGER . debug ( "Sending delete request [{}] to create table" , request ) ; TableUtils . createTableIfNotExists ( amazonDynamoDBClient , request ) ; LOGGER . debug ( "Waiting until table [{}] becomes active..." , request . getTableName ( ) ) ; TableUtils . waitUntilActive ( amazonDynamoDBClient , request . getTableName ( ) ) ; val describeTableRequest = new DescribeTableRequest ( ) . withTableName ( request . getTableName ( ) ) ; LOGGER . debug ( "Sending request [{}] to obtain table description..." , describeTableRequest ) ; val tableDescription = amazonDynamoDBClient . describeTable ( describeTableRequest ) . getTable ( ) ; LOGGER . debug ( "Located newly created table with description: [{}]" , tableDescription ) ; }
Create tables .
17,726
public Map < String , AttributeValue > buildTableAttributeValuesMapFromService ( final RegisteredService service ) { val values = new HashMap < String , AttributeValue > ( ) ; values . put ( ColumnNames . ID . getColumnName ( ) , new AttributeValue ( String . valueOf ( service . getId ( ) ) ) ) ; values . put ( ColumnNames . NAME . getColumnName ( ) , new AttributeValue ( service . getName ( ) ) ) ; values . put ( ColumnNames . DESCRIPTION . getColumnName ( ) , new AttributeValue ( service . getDescription ( ) ) ) ; values . put ( ColumnNames . SERVICE_ID . getColumnName ( ) , new AttributeValue ( service . getServiceId ( ) ) ) ; val out = new ByteArrayOutputStream ( ) ; jsonSerializer . to ( out , service ) ; values . put ( ColumnNames . ENCODED . getColumnName ( ) , new AttributeValue ( ) . withB ( ByteBuffer . wrap ( out . toByteArray ( ) ) ) ) ; LOGGER . debug ( "Created attribute values [{}] based on provided service [{}]" , values , service ) ; return values ; }
Build table attribute values from map .
17,727
protected void createDeviceFingerPrintCookie ( final RequestContext context , final HttpServletRequest request , final String cookieValue ) { val response = WebUtils . getHttpServletResponseFromExternalWebflowContext ( context ) ; cookieGenerator . addCookie ( request , response , cookieValue ) ; }
Create device finger print cookie .
17,728
public Map < String , Object > resolvePrincipalAttributes ( final String uid ) { val p = defaultPrincipalResolver . resolve ( new BasicIdentifiableCredential ( uid ) ) ; val map = new HashMap < String , Object > ( ) ; map . put ( "uid" , p . getId ( ) ) ; map . put ( "attributes" , p . getAttributes ( ) ) ; return map ; }
Resolve principal attributes map .
17,729
@ View ( name = "by_surrogate" , map = "function(doc) { if(doc.surrogate && doc.principal) { emit(doc.principal, doc.surrogate) } }" ) public List < String > findByPrincipal ( final String surrogate ) { val view = createQuery ( "by_surrogate" ) . key ( surrogate ) ; return db . queryView ( view , String . class ) ; }
Find by surrogate .
17,730
@ View ( name = "by_surrogate_principal" , map = "function(doc) { if(doc.surrogate && doc.principal) { emit([doc.principal, doc.surrogate], doc) } }" ) public List < CouchDbSurrogateAuthorization > findBySurrogatePrincipal ( final String surrogate , final String principal ) { return queryView ( "by_surrogate_principal" , ComplexKey . of ( principal , surrogate ) ) ; }
Find by surrogate principal service touple for authorization check .
17,731
private static X509KeyManager getKeyManager ( final String algorithm , final KeyStore keystore , final char [ ] password ) throws Exception { val factory = KeyManagerFactory . getInstance ( algorithm ) ; factory . init ( keystore , password ) ; return ( X509KeyManager ) factory . getKeyManagers ( ) [ 0 ] ; }
Gets key manager .
17,732
private static Collection < X509TrustManager > getTrustManager ( final String algorithm , final KeyStore keystore ) throws Exception { val factory = TrustManagerFactory . getInstance ( algorithm ) ; factory . init ( keystore ) ; return Arrays . stream ( factory . getTrustManagers ( ) ) . filter ( e -> e instanceof X509TrustManager ) . map ( X509TrustManager . class :: cast ) . collect ( Collectors . toList ( ) ) ; }
Gets trust manager .
17,733
public void setDynamicallyRegistered ( final boolean dynamicallyRegistered ) { if ( dynamicallyRegistered && ! this . dynamicallyRegistered && dynamicRegistrationDateTime == null ) { setDynamicRegistrationDateTime ( ZonedDateTime . now ( ZoneOffset . UTC ) ) ; } this . dynamicallyRegistered = dynamicallyRegistered ; }
Indicates the service was dynamically registered . Records the registration time automatically .
17,734
public ResourceSet asResourceSet ( final CommonProfile profileResult ) { val resourceSet = new ResourceSet ( ) ; resourceSet . setIconUri ( getIconUri ( ) ) ; resourceSet . setId ( getId ( ) ) ; resourceSet . setName ( getName ( ) ) ; resourceSet . setScopes ( new HashSet < > ( getScopes ( ) ) ) ; resourceSet . setUri ( getUri ( ) ) ; resourceSet . setType ( getType ( ) ) ; resourceSet . setOwner ( profileResult . getId ( ) ) ; resourceSet . setClientId ( OAuth20Utils . getClientIdFromAuthenticatedProfile ( profileResult ) ) ; return resourceSet ; }
As resource set .
17,735
public void setAttribute ( final String key , final Object value ) { attributes . put ( key , CollectionUtils . toCollection ( value , ArrayList . class ) ) ; }
Sets a single attribute .
17,736
protected RedirectAction build ( final CasClient casClient , final WebContext context , final boolean renew , final boolean gateway ) { val serviceUrl = casClient . computeFinalCallbackUrl ( context ) ; val casServerLoginUrl = casClient . getConfiguration ( ) . getLoginUrl ( ) ; val redirectionUrl = casServerLoginUrl + ( casServerLoginUrl . contains ( "?" ) ? "&" : "?" ) + CasProtocolConstants . PARAMETER_SERVICE + '=' + EncodingUtils . urlEncode ( serviceUrl ) + ( renew ? '&' + CasProtocolConstants . PARAMETER_RENEW + "=true" : StringUtils . EMPTY ) + ( gateway ? '&' + CasProtocolConstants . PARAMETER_GATEWAY + "=true" : StringUtils . EMPTY ) ; LOGGER . debug ( "Final redirect url is [{}]" , redirectionUrl ) ; return RedirectAction . redirect ( redirectionUrl ) ; }
Build with predefined renew and gateway parameters .
17,737
public void handleRefreshEvent ( final RefreshRemoteApplicationEvent event ) { LOGGER . trace ( "Received event [{}]" , event ) ; configurationPropertiesEnvironmentManager . rebindCasConfigurationProperties ( this . applicationContext ) ; }
Handle refresh event when issued by the cloud bus .
17,738
protected void signAssertion ( final Assertion assertion , final HttpServletRequest request , final HttpServletResponse response , final SamlRegisteredService service , final SamlRegisteredServiceServiceProviderMetadataFacade adaptor , final String binding , final RequestAbstractType authnRequest ) throws SamlException { if ( service . isSignAssertions ( ) ) { LOGGER . debug ( "SAML registered service [{}] requires assertions to be signed" , adaptor . getEntityId ( ) ) ; samlObjectSigner . encode ( assertion , service , adaptor , response , request , binding , authnRequest ) ; } else { LOGGER . debug ( "SAML registered service [{}] does not require assertions to be signed" , adaptor . getEntityId ( ) ) ; } }
Sign assertion .
17,739
public static LogEvent prepareLogEvent ( final LogEvent logEvent ) { val messageModified = TicketIdSanitizationUtils . sanitize ( logEvent . getMessage ( ) . getFormattedMessage ( ) ) ; val message = new SimpleMessage ( messageModified ) ; val newLogEventBuilder = Log4jLogEvent . newBuilder ( ) . setLevel ( logEvent . getLevel ( ) ) . setLoggerName ( logEvent . getLoggerName ( ) ) . setLoggerFqcn ( logEvent . getLoggerFqcn ( ) ) . setContextData ( new SortedArrayStringMap ( logEvent . getContextData ( ) ) ) . setContextStack ( logEvent . getContextStack ( ) ) . setEndOfBatch ( logEvent . isEndOfBatch ( ) ) . setIncludeLocation ( logEvent . isIncludeLocation ( ) ) . setMarker ( logEvent . getMarker ( ) ) . setMessage ( message ) . setNanoTime ( logEvent . getNanoTime ( ) ) . setThreadName ( logEvent . getThreadName ( ) ) . setThrownProxy ( logEvent . getThrownProxy ( ) ) . setThrown ( logEvent . getThrown ( ) ) . setTimeMillis ( logEvent . getTimeMillis ( ) ) ; try { newLogEventBuilder . setSource ( logEvent . getSource ( ) ) ; } catch ( final Exception e ) { newLogEventBuilder . setSource ( null ) ; } return newLogEventBuilder . build ( ) ; }
Prepare log event log event .
17,740
public static void printAsciiArtInfo ( final Logger out , final String asciiArt , final String additional ) { out . info ( ANSI_CYAN ) ; out . info ( "\n\n" . concat ( FigletFont . convertOneLine ( asciiArt ) ) . concat ( additional ) ) ; out . info ( ANSI_RESET ) ; }
Print ascii art info .
17,741
public static TicketGrantingTicket getTicketGrantingTicketFromRequest ( final CasCookieBuilder ticketGrantingTicketCookieGenerator , final TicketRegistry ticketRegistry , final HttpServletRequest request ) { val cookieValue = ticketGrantingTicketCookieGenerator . retrieveCookieValue ( request ) ; if ( StringUtils . isNotBlank ( cookieValue ) ) { val tgt = ticketRegistry . getTicket ( cookieValue , TicketGrantingTicket . class ) ; if ( tgt != null && ! tgt . isExpired ( ) ) { return tgt ; } } return null ; }
Gets ticket granting ticket from request .
17,742
public static Optional < Cookie > getCookieFromRequest ( final String cookieName , final HttpServletRequest request ) { val cookies = request . getCookies ( ) ; if ( cookies == null ) { return Optional . empty ( ) ; } return Arrays . stream ( cookies ) . filter ( c -> c . getName ( ) . equalsIgnoreCase ( cookieName ) ) . findFirst ( ) ; }
Gets cookie from request .
17,743
public static CookieGenerationContext buildCookieGenerationContext ( final TicketGrantingCookieProperties cookie ) { val rememberMeMaxAge = ( int ) Beans . newDuration ( cookie . getRememberMeMaxAge ( ) ) . getSeconds ( ) ; val builder = buildCookieGenerationContextBuilder ( cookie ) ; return builder . rememberMeMaxAge ( rememberMeMaxAge ) . build ( ) ; }
Build cookie generation context cookie .
17,744
private static Principal getPrimaryPrincipal ( final PrincipalElectionStrategy principalElectionStrategy , final Set < Authentication > authentications , final Map < String , List < Object > > principalAttributes ) { return principalElectionStrategy . nominate ( new LinkedHashSet < > ( authentications ) , principalAttributes ) ; }
Principal id is and must be enforced to be the same for all authentications . Based on that restriction it s safe to simply grab the first principal id in the chain when composing the authentication chain for the caller .
17,745
protected void addAuthenticationMethodAttribute ( final AuthenticationBuilder builder , final Authentication authentication ) { authentication . getSuccesses ( ) . values ( ) . forEach ( result -> builder . addAttribute ( AUTHENTICATION_METHOD_ATTRIBUTE , result . getHandlerName ( ) ) ) ; }
Add authentication method attribute .
17,746
protected Principal resolvePrincipal ( final AuthenticationHandler handler , final PrincipalResolver resolver , final Credential credential , final Principal principal ) { if ( resolver . supports ( credential ) ) { try { val p = resolver . resolve ( credential , Optional . ofNullable ( principal ) , Optional . ofNullable ( handler ) ) ; LOGGER . debug ( "[{}] resolved [{}] from [{}]" , resolver , p , credential ) ; return p ; } catch ( final Exception e ) { LOGGER . error ( "[{}] failed to resolve principal from [{}]" , resolver , credential , e ) ; } } else { LOGGER . warn ( "[{}] is configured to use [{}] but it does not support [{}], which suggests a configuration problem." , handler . getName ( ) , resolver , credential ) ; } return null ; }
Resolve principal .
17,747
protected boolean invokeAuthenticationPreProcessors ( final AuthenticationTransaction transaction ) { LOGGER . trace ( "Invoking authentication pre processors for authentication transaction" ) ; val pops = authenticationEventExecutionPlan . getAuthenticationPreProcessors ( transaction ) ; final Collection < AuthenticationPreProcessor > supported = pops . stream ( ) . filter ( processor -> transaction . getCredentials ( ) . stream ( ) . anyMatch ( processor :: supports ) ) . collect ( Collectors . toList ( ) ) ; var processed = true ; val it = supported . iterator ( ) ; while ( processed && it . hasNext ( ) ) { val processor = it . next ( ) ; processed = processor . process ( transaction ) ; } return processed ; }
Invoke authentication pre processors .
17,748
protected void authenticateAndResolvePrincipal ( final AuthenticationBuilder builder , final Credential credential , final PrincipalResolver resolver , final AuthenticationHandler handler ) throws GeneralSecurityException , PreventedException { publishEvent ( new CasAuthenticationTransactionStartedEvent ( this , credential ) ) ; val result = handler . authenticate ( credential ) ; val authenticationHandlerName = handler . getName ( ) ; builder . addSuccess ( authenticationHandlerName , result ) ; LOGGER . debug ( "Authentication handler [{}] successfully authenticated [{}]" , authenticationHandlerName , credential ) ; publishEvent ( new CasAuthenticationTransactionSuccessfulEvent ( this , credential ) ) ; var principal = result . getPrincipal ( ) ; val resolverName = resolver != null ? resolver . getName ( ) : "N/A" ; if ( resolver == null ) { LOGGER . debug ( "No principal resolution is configured for [{}]. Falling back to handler principal [{}]" , authenticationHandlerName , principal ) ; } else { principal = resolvePrincipal ( handler , resolver , credential , principal ) ; if ( principal == null ) { if ( this . principalResolutionFailureFatal ) { LOGGER . warn ( "Principal resolution handled by [{}] produced a null principal for: [{}]" + "CAS is configured to treat principal resolution failures as fatal." , resolverName , credential ) ; throw new UnresolvedPrincipalException ( ) ; } LOGGER . warn ( "Principal resolution handled by [{}] produced a null principal. " + "This is likely due to misconfiguration or missing attributes; CAS will attempt to use the principal " + "produced by the authentication handler, if any." , resolver . getClass ( ) . getSimpleName ( ) ) ; } } if ( principal == null ) { LOGGER . warn ( "Principal resolution for authentication by [{}] produced a null principal." , authenticationHandlerName ) ; } else { builder . setPrincipal ( principal ) ; } LOGGER . debug ( "Final principal resolved for this authentication event is [{}]" , principal ) ; publishEvent ( new CasAuthenticationPrincipalResolvedEvent ( this , principal ) ) ; }
Authenticate and resolve principal .
17,749
protected PrincipalResolver getPrincipalResolverLinkedToHandlerIfAny ( final AuthenticationHandler handler , final AuthenticationTransaction transaction ) { return this . authenticationEventExecutionPlan . getPrincipalResolverForAuthenticationTransaction ( handler , transaction ) ; }
Gets principal resolver linked to the handler if any .
17,750
protected AuthenticationBuilder authenticateInternal ( final AuthenticationTransaction transaction ) throws AuthenticationException { val credentials = transaction . getCredentials ( ) ; LOGGER . debug ( "Authentication credentials provided for this transaction are [{}]" , credentials ) ; if ( credentials . isEmpty ( ) ) { LOGGER . error ( "Resolved authentication handlers for this transaction are empty" ) ; throw new AuthenticationException ( "Resolved credentials for this transaction are empty" ) ; } val builder = new DefaultAuthenticationBuilder ( NullPrincipal . getInstance ( ) ) ; credentials . forEach ( cred -> builder . addCredential ( new BasicCredentialMetaData ( cred ) ) ) ; val handlerSet = this . authenticationEventExecutionPlan . getAuthenticationHandlersForTransaction ( transaction ) ; LOGGER . debug ( "Candidate resolved authentication handlers for this transaction are [{}]" , handlerSet ) ; if ( handlerSet . isEmpty ( ) ) { LOGGER . error ( "Resolved authentication handlers for this transaction are empty" ) ; throw new AuthenticationException ( builder . getFailures ( ) , builder . getSuccesses ( ) ) ; } try { val it = credentials . iterator ( ) ; AuthenticationCredentialsThreadLocalBinder . clearInProgressAuthentication ( ) ; while ( it . hasNext ( ) ) { val credential = it . next ( ) ; LOGGER . debug ( "Attempting to authenticate credential [{}]" , credential ) ; val itHandlers = handlerSet . iterator ( ) ; var proceedWithNextHandler = true ; while ( proceedWithNextHandler && itHandlers . hasNext ( ) ) { val handler = itHandlers . next ( ) ; if ( handler . supports ( credential ) ) { try { val resolver = getPrincipalResolverLinkedToHandlerIfAny ( handler , transaction ) ; LOGGER . debug ( "Attempting authentication of [{}] using [{}]" , credential . getId ( ) , handler . getName ( ) ) ; authenticateAndResolvePrincipal ( builder , credential , resolver , handler ) ; val authnResult = builder . build ( ) ; AuthenticationCredentialsThreadLocalBinder . bindInProgress ( authnResult ) ; val failures = evaluateAuthenticationPolicies ( authnResult , transaction , handlerSet ) ; proceedWithNextHandler = ! failures . getKey ( ) ; } catch ( final Exception e ) { LOGGER . error ( "Authentication has failed. Credentials may be incorrect or CAS cannot " + "find authentication handler that supports [{}] of type [{}]. Examine the configuration to " + "ensure a method of authentication is defined and analyze CAS logs at DEBUG level to trace " + "the authentication event." , credential , credential . getClass ( ) . getSimpleName ( ) ) ; handleAuthenticationException ( e , handler . getName ( ) , builder ) ; proceedWithNextHandler = true ; } } else { LOGGER . debug ( "Authentication handler [{}] does not support the credential type [{}]. Trying next..." , handler . getName ( ) , credential ) ; } } } evaluateFinalAuthentication ( builder , transaction , handlerSet ) ; return builder ; } finally { AuthenticationCredentialsThreadLocalBinder . clearInProgressAuthentication ( ) ; } }
Authenticate internal authentication builder .
17,751
protected void evaluateFinalAuthentication ( final AuthenticationBuilder builder , final AuthenticationTransaction transaction , final Set < AuthenticationHandler > authenticationHandlers ) throws AuthenticationException { if ( builder . getSuccesses ( ) . isEmpty ( ) ) { publishEvent ( new CasAuthenticationTransactionFailureEvent ( this , builder . getFailures ( ) , transaction . getCredentials ( ) ) ) ; throw new AuthenticationException ( builder . getFailures ( ) , builder . getSuccesses ( ) ) ; } val authentication = builder . build ( ) ; val failures = evaluateAuthenticationPolicies ( authentication , transaction , authenticationHandlers ) ; if ( ! failures . getKey ( ) ) { publishEvent ( new CasAuthenticationPolicyFailureEvent ( this , builder . getFailures ( ) , transaction , authentication ) ) ; failures . getValue ( ) . forEach ( e -> handleAuthenticationException ( e , e . getClass ( ) . getSimpleName ( ) , builder ) ) ; throw new AuthenticationException ( builder . getFailures ( ) , builder . getSuccesses ( ) ) ; } }
Evaluate produced authentication context . We apply an implicit security policy of at least one successful authentication . Then we apply the configured security policy .
17,752
protected Pair < Boolean , Set < Throwable > > evaluateAuthenticationPolicies ( final Authentication authentication , final AuthenticationTransaction transaction , final Set < AuthenticationHandler > authenticationHandlers ) { val failures = new LinkedHashSet < Throwable > ( ) ; val policies = authenticationEventExecutionPlan . getAuthenticationPolicies ( transaction ) ; policies . forEach ( p -> { try { val simpleName = p . getClass ( ) . getSimpleName ( ) ; LOGGER . debug ( "Executing authentication policy [{}]" , simpleName ) ; val supportingHandlers = authenticationHandlers . stream ( ) . filter ( handler -> transaction . getCredentials ( ) . stream ( ) . anyMatch ( handler :: supports ) ) . collect ( Collectors . toCollection ( LinkedHashSet :: new ) ) ; if ( ! p . isSatisfiedBy ( authentication , supportingHandlers ) ) { failures . add ( new AuthenticationException ( "Unable to satisfy authentication policy " + simpleName ) ) ; } } catch ( final GeneralSecurityException e ) { LOGGER . debug ( e . getMessage ( ) , e ) ; failures . add ( e . getCause ( ) ) ; } catch ( final Exception e ) { LOGGER . debug ( e . getMessage ( ) , e ) ; failures . add ( e ) ; } } ) ; return Pair . of ( failures . isEmpty ( ) , failures ) ; }
Evaluate authentication policies .
17,753
protected void handleAuthenticationException ( final Throwable ex , final String name , final AuthenticationBuilder builder ) { var e = ex ; if ( ex instanceof UndeclaredThrowableException ) { e = ( ( UndeclaredThrowableException ) ex ) . getUndeclaredThrowable ( ) ; } LOGGER . trace ( e . getMessage ( ) , e ) ; val msg = new StringBuilder ( StringUtils . defaultString ( e . getMessage ( ) ) ) ; if ( e . getCause ( ) != null ) { msg . append ( " / " ) . append ( e . getCause ( ) . getMessage ( ) ) ; } if ( e instanceof GeneralSecurityException ) { LOGGER . debug ( "[{}] exception details: [{}]." , name , msg ) ; builder . addFailure ( name , e ) ; } else { LOGGER . error ( "[{}]: [{}]" , name , msg ) ; builder . addFailure ( name , e ) ; } }
Handle authentication exception .
17,754
public CouchDbSamlIdPMetadataDocument getOne ( ) { val view = createQuery ( "all" ) . limit ( 1 ) ; return db . queryView ( view , CouchDbSamlIdPMetadataDocument . class ) . stream ( ) . findFirst ( ) . orElse ( null ) ; }
Get one SAML metadata document .
17,755
public Service resolveServiceFrom ( final Service service ) { val result = getEntityIdAsParameter ( service ) ; if ( result . isPresent ( ) ) { val entityId = result . get ( ) ; LOGGER . debug ( "Located entity id [{}] from service authentication request at [{}]" , entityId , service . getId ( ) ) ; if ( isEntityIdServiceRegistered ( entityId ) ) { return this . webApplicationServiceFactory . createService ( entityId ) ; } LOGGER . debug ( "Entity id [{}] not registered as individual service" , entityId ) ; } LOGGER . debug ( "Could not located entity id from service authentication request at [{}]" , service . getId ( ) ) ; return service ; }
Method attempts to resolve the service from the entityId parameter . If present an attempt is made to find a service corresponding to the entityId in the Service Registry . If a service is not resolved from a passed entity id the service = parameter of the request will be returned instead . This is usually the callback url to the external Shibboleth IdP .
17,756
protected MessageContext getEncoderMessageContext ( final RequestAbstractType request , final T samlObject , final String relayState ) { val ctx = new MessageContext < SAMLObject > ( ) ; ctx . setMessage ( samlObject ) ; SAMLBindingSupport . setRelayState ( ctx , relayState ) ; SamlIdPUtils . preparePeerEntitySamlEndpointContext ( request , ctx , adaptor , getBinding ( ) ) ; val self = ctx . getSubcontext ( SAMLSelfEntityContext . class , true ) ; self . setEntityId ( SamlIdPUtils . getIssuerFromSamlObject ( samlObject ) ) ; return ctx ; }
Build encoder message context .
17,757
protected void finalizeEncode ( final RequestAbstractType authnRequest , final BaseSAML2MessageEncoder encoder , final T samlResponse , final String relayState ) throws Exception { encoder . initialize ( ) ; encoder . encode ( ) ; }
Finalize encode response .
17,758
public static SamlRegisteredService newSamlServiceProviderService ( final AbstractSamlSPProperties sp , final SamlRegisteredServiceCachingMetadataResolver resolver ) { if ( StringUtils . isBlank ( sp . getMetadata ( ) ) ) { LOGGER . debug ( "Skipped registration of [{}] since no metadata location is found" , sp . getName ( ) ) ; return null ; } val service = new SamlRegisteredService ( ) ; service . setName ( sp . getName ( ) ) ; service . setDescription ( sp . getDescription ( ) ) ; service . setEvaluationOrder ( Ordered . HIGHEST_PRECEDENCE ) ; service . setMetadataLocation ( sp . getMetadata ( ) ) ; val attributesToRelease = new ArrayList < String > ( sp . getAttributes ( ) ) ; if ( StringUtils . isNotBlank ( sp . getNameIdAttribute ( ) ) ) { attributesToRelease . add ( sp . getNameIdAttribute ( ) ) ; service . setUsernameAttributeProvider ( new PrincipalAttributeRegisteredServiceUsernameProvider ( sp . getNameIdAttribute ( ) ) ) ; } if ( StringUtils . isNotBlank ( sp . getNameIdFormat ( ) ) ) { service . setRequiredNameIdFormat ( sp . getNameIdFormat ( ) ) ; } val attributes = CoreAuthenticationUtils . transformPrincipalAttributesListIntoMultiMap ( attributesToRelease ) ; val policy = new ChainingAttributeReleasePolicy ( ) ; policy . addPolicy ( new ReturnMappedAttributeReleasePolicy ( CollectionUtils . wrap ( attributes ) ) ) ; service . setAttributeReleasePolicy ( policy ) ; service . setMetadataCriteriaRoles ( SPSSODescriptor . DEFAULT_ELEMENT_NAME . getLocalPart ( ) ) ; service . setMetadataCriteriaRemoveEmptyEntitiesDescriptors ( true ) ; service . setMetadataCriteriaRemoveRolelessEntityDescriptors ( true ) ; if ( StringUtils . isNotBlank ( sp . getSignatureLocation ( ) ) ) { service . setMetadataSignatureLocation ( sp . getSignatureLocation ( ) ) ; } val entityIDList = determineEntityIdList ( sp , resolver , service ) ; if ( entityIDList . isEmpty ( ) ) { LOGGER . warn ( "Skipped registration of [{}] since no metadata entity ids could be found" , sp . getName ( ) ) ; return null ; } val entityIds = org . springframework . util . StringUtils . collectionToDelimitedString ( entityIDList , "|" ) ; service . setMetadataCriteriaDirection ( PredicateFilter . Direction . INCLUDE . name ( ) ) ; service . setMetadataCriteriaPattern ( entityIds ) ; LOGGER . debug ( "Registering saml service [{}] by entity id [{}]" , sp . getName ( ) , entityIds ) ; service . setServiceId ( entityIds ) ; service . setSignAssertions ( sp . isSignAssertions ( ) ) ; service . setSignResponses ( sp . isSignResponses ( ) ) ; return service ; }
New saml service provider registration .
17,759
public static void saveService ( final RegisteredService service , final ServicesManager servicesManager ) { servicesManager . load ( ) ; if ( servicesManager . findServiceBy ( registeredService -> registeredService instanceof SamlRegisteredService && registeredService . getServiceId ( ) . equals ( service . getServiceId ( ) ) ) . isEmpty ( ) ) { LOGGER . info ( "Service [{}] does not exist in the registry and will be added." , service . getServiceId ( ) ) ; servicesManager . save ( service ) ; servicesManager . load ( ) ; } else { LOGGER . info ( "Service [{}] exists in the registry and will not be added again." , service . getServiceId ( ) ) ; } }
Save service only if it s not already found in the registry .
17,760
public void createStateDefaultTransition ( final TransitionableState state , final String targetState ) { if ( state == null ) { LOGGER . trace ( "Cannot add default transition of [{}] to the given state is null and cannot be found in the flow." , targetState ) ; return ; } val transition = createTransition ( targetState ) ; state . getTransitionSet ( ) . add ( transition ) ; }
Add a default transition to a given state .
17,761
public Transition createTransitionForState ( final TransitionableState state , final String criteriaOutcome , final String targetState ) { return createTransitionForState ( state , criteriaOutcome , targetState , false ) ; }
Create transition for state transition .
17,762
public Transition createTransitionForState ( final TransitionableState state , final String criteriaOutcome , final String targetState , final boolean removeExisting ) { try { if ( removeExisting ) { val success = ( Transition ) state . getTransition ( criteriaOutcome ) ; if ( success != null ) { state . getTransitionSet ( ) . remove ( success ) ; } } val transition = createTransition ( criteriaOutcome , targetState ) ; state . getTransitionSet ( ) . add ( transition ) ; LOGGER . trace ( "Added transition [{}] to the state [{}]" , transition . getId ( ) , state . getId ( ) ) ; return transition ; } catch ( final Exception e ) { LOGGER . error ( e . getMessage ( ) , e ) ; } return null ; }
Add transition to action state .
17,763
public Expression createExpression ( final String expression , final Class expectedType ) { val parserContext = new FluentParserContext ( ) . expectResult ( expectedType ) ; return getSpringExpressionParser ( ) . parseExpression ( expression , parserContext ) ; }
Create expression expression .
17,764
public SpringELExpressionParser getSpringExpressionParser ( ) { val configuration = new SpelParserConfiguration ( ) ; val spelExpressionParser = new SpelExpressionParser ( configuration ) ; val parser = new SpringELExpressionParser ( spelExpressionParser , this . flowBuilderServices . getConversionService ( ) ) ; parser . addPropertyAccessor ( new ActionPropertyAccessor ( ) ) ; parser . addPropertyAccessor ( new BeanFactoryPropertyAccessor ( ) ) ; parser . addPropertyAccessor ( new FlowVariablePropertyAccessor ( ) ) ; parser . addPropertyAccessor ( new MapAdaptablePropertyAccessor ( ) ) ; parser . addPropertyAccessor ( new MessageSourcePropertyAccessor ( ) ) ; parser . addPropertyAccessor ( new ScopeSearchingPropertyAccessor ( ) ) ; parser . addPropertyAccessor ( new BeanExpressionContextAccessor ( ) ) ; parser . addPropertyAccessor ( new MapAccessor ( ) ) ; parser . addPropertyAccessor ( new MapAdaptablePropertyAccessor ( ) ) ; parser . addPropertyAccessor ( new EnvironmentAccessor ( ) ) ; parser . addPropertyAccessor ( new ReflectivePropertyAccessor ( ) ) ; return parser ; }
Gets spring expression parser .
17,765
public Mapper createMapperToSubflowState ( final List < DefaultMapping > mappings ) { val inputMapper = new DefaultMapper ( ) ; mappings . forEach ( inputMapper :: addMapping ) ; return inputMapper ; }
Create mapper to subflow state .
17,766
public DefaultMapping createMappingToSubflowState ( final String name , final String value , final boolean required , final Class type ) { val parser = this . flowBuilderServices . getExpressionParser ( ) ; val source = parser . parseExpression ( value , new FluentParserContext ( ) ) ; val target = parser . parseExpression ( name , new FluentParserContext ( ) ) ; val mapping = new DefaultMapping ( source , target ) ; mapping . setRequired ( required ) ; val typeConverter = new RuntimeBindingConversionExecutor ( type , this . flowBuilderServices . getConversionService ( ) ) ; mapping . setTypeConverter ( typeConverter ) ; return mapping ; }
Create mapping to subflow state .
17,767
public boolean containsFlowState ( final Flow flow , final String stateId ) { if ( flow == null ) { LOGGER . error ( "Flow is not configured correctly and cannot be null." ) ; return false ; } return flow . containsState ( stateId ) ; }
Contains flow state?
17,768
public boolean containsSubflowState ( final Flow flow , final String stateId ) { if ( containsFlowState ( flow , stateId ) ) { return getState ( flow , stateId , SubflowState . class ) != null ; } return false ; }
Contains subflow state .
17,769
public boolean containsTransition ( final TransitionableState state , final String transition ) { if ( state == null ) { LOGGER . error ( "State is not configured correctly and cannot be null." ) ; return false ; } return state . getTransition ( transition ) != null ; }
Contains transition boolean .
17,770
public FlowVariable createFlowVariable ( final Flow flow , final String id , final Class type ) { val opt = Arrays . stream ( flow . getVariables ( ) ) . filter ( v -> v . getName ( ) . equalsIgnoreCase ( id ) ) . findFirst ( ) ; if ( opt . isPresent ( ) ) { return opt . get ( ) ; } val flowVar = new FlowVariable ( id , new BeanFactoryVariableValueFactory ( type , applicationContext . getAutowireCapableBeanFactory ( ) ) ) ; flow . addVariable ( flowVar ) ; return flowVar ; }
Create flow variable flow variable .
17,771
public BinderConfiguration createStateBinderConfiguration ( final List < String > properties ) { val binder = new BinderConfiguration ( ) ; properties . forEach ( p -> binder . addBinding ( new BinderConfiguration . Binding ( p , null , true ) ) ) ; return binder ; }
Create state model bindings .
17,772
public void createStateModelBinding ( final TransitionableState state , final String modelName , final Class modelType ) { state . getAttributes ( ) . put ( "model" , createExpression ( modelName , modelType ) ) ; }
Create state model binding .
17,773
public BinderConfiguration getViewStateBinderConfiguration ( final ViewState state ) { val field = ReflectionUtils . findField ( state . getViewFactory ( ) . getClass ( ) , "binderConfiguration" ) ; ReflectionUtils . makeAccessible ( field ) ; return ( BinderConfiguration ) ReflectionUtils . getField ( field , state . getViewFactory ( ) ) ; }
Gets state binder configuration .
17,774
public void cloneActionState ( final ActionState source , final ActionState target ) { source . getActionList ( ) . forEach ( a -> target . getActionList ( ) . add ( a ) ) ; source . getExitActionList ( ) . forEach ( a -> target . getExitActionList ( ) . add ( a ) ) ; source . getAttributes ( ) . asMap ( ) . forEach ( ( k , v ) -> target . getAttributes ( ) . put ( k , v ) ) ; source . getTransitionSet ( ) . forEach ( t -> target . getTransitionSet ( ) . addAll ( t ) ) ; val field = ReflectionUtils . findField ( target . getExceptionHandlerSet ( ) . getClass ( ) , "exceptionHandlers" ) ; ReflectionUtils . makeAccessible ( field ) ; val list = ( List < FlowExecutionExceptionHandler > ) ReflectionUtils . getField ( field , target . getExceptionHandlerSet ( ) ) ; list . forEach ( h -> source . getExceptionHandlerSet ( ) . add ( h ) ) ; target . setDescription ( source . getDescription ( ) ) ; target . setCaption ( source . getCaption ( ) ) ; }
Clone action state .
17,775
public List < TransitionCriteria > getTransitionExecutionCriteriaChainForTransition ( final Transition def ) { if ( def . getExecutionCriteria ( ) instanceof TransitionCriteriaChain ) { val chain = ( TransitionCriteriaChain ) def . getExecutionCriteria ( ) ; val field = ReflectionUtils . findField ( chain . getClass ( ) , "criteriaChain" ) ; ReflectionUtils . makeAccessible ( field ) ; return ( List < TransitionCriteria > ) ReflectionUtils . getField ( field , chain ) ; } if ( def . getExecutionCriteria ( ) != null ) { return CollectionUtils . wrapList ( def . getExecutionCriteria ( ) ) ; } return new ArrayList < > ( 0 ) ; }
Gets transition execution criteria chain for transition .
17,776
public Expression getExpressionStringFromAction ( final EvaluateAction act ) { val field = ReflectionUtils . findField ( act . getClass ( ) , "expression" ) ; ReflectionUtils . makeAccessible ( field ) ; return ( Expression ) ReflectionUtils . getField ( field , act ) ; }
Gets expression string from action .
17,777
public Action createEvaluateActionForExistingActionState ( final Flow flow , final String actionStateId , final String evaluateActionId ) { val action = getState ( flow , actionStateId , ActionState . class ) ; val actions = action . getActionList ( ) . toArray ( ) ; Arrays . stream ( actions ) . forEach ( action . getActionList ( ) :: remove ) ; val evaluateAction = createEvaluateAction ( evaluateActionId ) ; action . getActionList ( ) . add ( evaluateAction ) ; action . getActionList ( ) . addAll ( actions ) ; return evaluateAction ; }
Create evaluate action for action state action .
17,778
public void createClonedActionState ( final Flow flow , final String actionStateId , final String actionStateIdToClone ) { val generateServiceTicket = getState ( flow , actionStateIdToClone , ActionState . class ) ; val consentTicketAction = createActionState ( flow , actionStateId ) ; cloneActionState ( generateServiceTicket , consentTicketAction ) ; }
Clone and create action state .
17,779
public TransitionableState getTransitionableState ( final Flow flow , final String stateId ) { if ( containsFlowState ( flow , stateId ) ) { return ( TransitionableState ) flow . getTransitionableState ( stateId ) ; } return null ; }
Gets transitionable state .
17,780
public void createTransitionsForState ( final Flow flow , final String stateId , final Map < String , String > criteriaAndTargets ) { if ( containsFlowState ( flow , stateId ) ) { val state = getState ( flow , stateId ) ; criteriaAndTargets . forEach ( ( k , v ) -> createTransitionForState ( state , k , v ) ) ; } }
Create transitions for state .
17,781
public void appendActionsToActionStateExecutionList ( final Flow flow , final String actionStateId , final EvaluateAction ... actions ) { addActionsToActionStateExecutionListAt ( flow , actionStateId , Integer . MAX_VALUE , actions ) ; }
Append actions to action state execution list .
17,782
public void addActionsToActionStateExecutionListAt ( final Flow flow , final String actionStateId , final int position , final EvaluateAction ... actions ) { val actionState = getState ( flow , actionStateId , ActionState . class ) ; val currentActions = new ArrayList < Action > ( ) ; val actionList = actionState . getActionList ( ) ; actionList . forEach ( currentActions :: add ) ; val index = position < 0 || position == Integer . MAX_VALUE ? currentActions . size ( ) : position ; currentActions . forEach ( actionList :: remove ) ; Arrays . stream ( actions ) . forEach ( a -> currentActions . add ( index , a ) ) ; actionList . addAll ( currentActions . toArray ( Action [ ] :: new ) ) ; }
Add actions to action state execution list at .
17,783
protected void publishInternal ( final RegisteredService service , final ApplicationEvent event ) { if ( event instanceof CasRegisteredServiceDeletedEvent ) { handleCasRegisteredServiceDeletedEvent ( service , event ) ; return ; } if ( event instanceof CasRegisteredServiceSavedEvent || event instanceof CasRegisteredServiceLoadedEvent ) { handleCasRegisteredServiceUpdateEvents ( service , event ) ; return ; } LOGGER . warn ( "Unsupported event [{}} for service replication" , event ) ; }
Publish internal .
17,784
protected Set < Event > resolveEventsInternal ( final Set < Event > resolveEvents , final Authentication authentication , final RegisteredService registeredService , final HttpServletRequest request , final RequestContext context ) { if ( ! resolveEvents . isEmpty ( ) ) { LOGGER . trace ( "Collection of resolved events for this authentication sequence are:" ) ; resolveEvents . forEach ( e -> LOGGER . trace ( "Event id [{}] resolved from [{}]" , e . getId ( ) , e . getSource ( ) . getClass ( ) . getName ( ) ) ) ; } else { LOGGER . trace ( "No events could be resolved for this authentication transaction [{}] and service [{}]" , authentication , registeredService ) ; } val pair = filterEventsByMultifactorAuthenticationProvider ( resolveEvents , authentication , registeredService , request ) ; WebUtils . putResolvedMultifactorAuthenticationProviders ( context , pair . getValue ( ) ) ; return pair . getKey ( ) ; }
Resolve events internal set . Implementation may filter events from the collection to only return the one that is appropriate for this request . The default implementation returns the entire collection .
17,785
protected Pair < Set < Event > , Collection < MultifactorAuthenticationProvider > > filterEventsByMultifactorAuthenticationProvider ( final Set < Event > resolveEvents , final Authentication authentication , final RegisteredService registeredService , final HttpServletRequest request ) { LOGGER . debug ( "Locating multifactor providers to determine support for this authentication sequence" ) ; val providers = MultifactorAuthenticationUtils . getAvailableMultifactorAuthenticationProviders ( getWebflowEventResolutionConfigurationContext ( ) . getApplicationContext ( ) ) ; if ( providers . isEmpty ( ) ) { LOGGER . debug ( "No providers are available to honor this request. Moving on..." ) ; return Pair . of ( resolveEvents , new HashSet < > ( 0 ) ) ; } val providerValues = providers . values ( ) ; providerValues . removeIf ( p -> resolveEvents . stream ( ) . noneMatch ( e -> p . matches ( e . getId ( ) ) ) ) ; resolveEvents . removeIf ( e -> providerValues . stream ( ) . noneMatch ( p -> p . matches ( e . getId ( ) ) ) ) ; LOGGER . debug ( "Finalized set of resolved events are [{}]" , resolveEvents ) ; return Pair . of ( resolveEvents , providerValues ) ; }
Filter events by multifactor authentication providers .
17,786
protected Map < String , List < Object > > getPrincipalAttributesFromReleasePolicy ( final Principal p , final Service service , final RegisteredService registeredService ) { if ( registeredService != null && registeredService . getAccessStrategy ( ) . isServiceAccessAllowed ( ) ) { LOGGER . debug ( "Located service [{}] in the registry. Attempting to resolve attributes for [{}]" , registeredService , p . getId ( ) ) ; if ( registeredService . getAttributeReleasePolicy ( ) == null ) { LOGGER . debug ( "No attribute release policy is defined for [{}]. Returning default principal attributes" , service . getId ( ) ) ; return p . getAttributes ( ) ; } return registeredService . getAttributeReleasePolicy ( ) . getAttributes ( p , service , registeredService ) ; } LOGGER . debug ( "Could not locate service [{}] in the registry." , service . getId ( ) ) ; throw new UnauthorizedServiceException ( UnauthorizedServiceException . CODE_UNAUTHZ_SERVICE ) ; }
Gets principal attributes . Will attempt to locate the principal attribute repository from the context if one is defined to use that instance to locate attributes . If none is available will use the default principal attributes .
17,787
public IgniteConfiguration igniteConfiguration ( @ Qualifier ( "ticketCatalog" ) final TicketCatalog ticketCatalog ) { val ignite = casProperties . getTicket ( ) . getRegistry ( ) . getIgnite ( ) ; val config = new IgniteConfiguration ( ) ; val spi = new TcpDiscoverySpi ( ) ; if ( ! StringUtils . isEmpty ( ignite . getLocalAddress ( ) ) ) { spi . setLocalAddress ( ignite . getLocalAddress ( ) ) ; } if ( ignite . getLocalPort ( ) != - 1 ) { spi . setLocalPort ( ignite . getLocalPort ( ) ) ; } spi . setJoinTimeout ( Beans . newDuration ( ignite . getJoinTimeout ( ) ) . toMillis ( ) ) ; spi . setAckTimeout ( Beans . newDuration ( ignite . getAckTimeout ( ) ) . toMillis ( ) ) ; spi . setNetworkTimeout ( Beans . newDuration ( ignite . getNetworkTimeout ( ) ) . toMillis ( ) ) ; spi . setSocketTimeout ( Beans . newDuration ( ignite . getSocketTimeout ( ) ) . toMillis ( ) ) ; spi . setThreadPriority ( ignite . getThreadPriority ( ) ) ; spi . setForceServerMode ( ignite . isForceServerMode ( ) ) ; val finder = new TcpDiscoveryVmIpFinder ( ) ; finder . setAddresses ( ignite . getIgniteAddress ( ) ) ; spi . setIpFinder ( finder ) ; config . setDiscoverySpi ( spi ) ; val cacheConfigurations = buildIgniteTicketCaches ( ignite , ticketCatalog ) ; config . setCacheConfiguration ( cacheConfigurations . toArray ( CacheConfiguration [ ] :: new ) ) ; config . setClientMode ( ignite . isClientMode ( ) ) ; val factory = buildSecureTransportForIgniteConfiguration ( ) ; if ( factory != null ) { config . setSslContextFactory ( factory ) ; } val dataStorageConfiguration = new DataStorageConfiguration ( ) ; val dataRegionConfiguration = new DataRegionConfiguration ( ) ; dataRegionConfiguration . setName ( "DefaultRegion" ) ; dataRegionConfiguration . setMaxSize ( ignite . getDefaultRegionMaxSize ( ) ) ; dataRegionConfiguration . setPersistenceEnabled ( ignite . isDefaultPersistenceEnabled ( ) ) ; dataStorageConfiguration . setDefaultDataRegionConfiguration ( dataRegionConfiguration ) ; dataStorageConfiguration . setSystemRegionMaxSize ( ignite . getDefaultRegionMaxSize ( ) ) ; config . setDataStorageConfiguration ( dataStorageConfiguration ) ; if ( LOGGER . isDebugEnabled ( ) ) { LOGGER . debug ( "igniteConfiguration.cacheConfiguration=[{}]" , ( Object [ ] ) config . getCacheConfiguration ( ) ) ; LOGGER . debug ( "igniteConfiguration.getDiscoverySpi=[{}]" , config . getDiscoverySpi ( ) ) ; LOGGER . debug ( "igniteConfiguration.getSslContextFactory=[{}]" , config . getSslContextFactory ( ) ) ; } return config ; }
Ignite configuration ignite configuration .
17,788
public static PrincipalNameTransformer newPrincipalNameTransformer ( final PrincipalTransformationProperties p ) { val chain = new ChainingPrincipalNameTransformer ( ) ; if ( p . getGroovy ( ) . getLocation ( ) != null ) { val t = new GroovyPrincipalNameTransformer ( p . getGroovy ( ) . getLocation ( ) ) ; chain . addTransformer ( t ) ; } if ( StringUtils . isNotBlank ( p . getPattern ( ) ) ) { val t = new RegexPrincipalNameTransformer ( p . getPattern ( ) ) ; chain . addTransformer ( t ) ; } if ( StringUtils . isNotBlank ( p . getPrefix ( ) ) || StringUtils . isNotBlank ( p . getSuffix ( ) ) ) { val t = new PrefixSuffixPrincipalNameTransformer ( ) ; t . setPrefix ( p . getPrefix ( ) ) ; t . setSuffix ( p . getSuffix ( ) ) ; chain . addTransformer ( t ) ; } else { chain . addTransformer ( new NoOpPrincipalNameTransformer ( ) ) ; } if ( p . getCaseConversion ( ) == PrincipalTransformationProperties . CaseConversion . UPPERCASE ) { val t = new ConvertCasePrincipalNameTransformer ( ) ; t . setToUpperCase ( true ) ; chain . addTransformer ( t ) ; } if ( p . getCaseConversion ( ) == PrincipalTransformationProperties . CaseConversion . LOWERCASE ) { val t = new ConvertCasePrincipalNameTransformer ( ) ; t . setToUpperCase ( false ) ; chain . addTransformer ( t ) ; } return chain ; }
New principal name transformer .
17,789
protected Pair < String , Map < String , List < Object > > > convertPersonAttributesToPrincipal ( final String extractedPrincipalId , final Map < String , List < Object > > attributes ) { val convertedAttributes = new LinkedHashMap < String , List < Object > > ( ) ; attributes . forEach ( ( key , attrValue ) -> { val values = CollectionUtils . toCollection ( attrValue , ArrayList . class ) ; LOGGER . debug ( "Found attribute [{}] with value(s) [{}]" , key , values ) ; if ( values . size ( ) == 1 ) { val value = CollectionUtils . firstElement ( values ) . get ( ) ; convertedAttributes . put ( key , CollectionUtils . wrapList ( value ) ) ; } else { convertedAttributes . put ( key , values ) ; } } ) ; var principalId = extractedPrincipalId ; if ( StringUtils . isNotBlank ( this . principalAttributeNames ) ) { val attrNames = org . springframework . util . StringUtils . commaDelimitedListToSet ( this . principalAttributeNames ) ; val result = attrNames . stream ( ) . map ( String :: trim ) . filter ( attributes :: containsKey ) . map ( attributes :: get ) . findFirst ( ) ; if ( result . isPresent ( ) ) { val values = result . get ( ) ; if ( ! values . isEmpty ( ) ) { principalId = CollectionUtils . firstElement ( values ) . get ( ) . toString ( ) ; LOGGER . debug ( "Found principal id attribute value [{}] and removed it from the collection of attributes" , principalId ) ; } } else { LOGGER . warn ( "Principal resolution is set to resolve the authenticated principal via attribute(s) [{}], and yet " + "the collection of attributes retrieved [{}] do not contain any of those attributes. This is likely due to misconfiguration " + "and CAS will switch to use [{}] as the final principal id" , this . principalAttributeNames , attributes . keySet ( ) , principalId ) ; } } return Pair . of ( principalId , convertedAttributes ) ; }
Convert person attributes to principal pair .
17,790
protected Map < String , List < Object > > retrievePersonAttributes ( final String principalId , final Credential credential ) { return CoreAuthenticationUtils . retrieveAttributesFromAttributeRepository ( this . attributeRepository , principalId , activeAttributeRepositoryIdentifiers ) ; }
Retrieve person attributes map .
17,791
protected String extractPrincipalId ( final Credential credential , final Optional < Principal > currentPrincipal ) { LOGGER . debug ( "Extracting credential id based on existing credential [{}]" , credential ) ; val id = credential . getId ( ) ; if ( currentPrincipal != null && currentPrincipal . isPresent ( ) ) { val principal = currentPrincipal . get ( ) ; LOGGER . debug ( "Principal is currently resolved as [{}]" , principal ) ; if ( useCurrentPrincipalId ) { LOGGER . debug ( "Using the existing resolved principal id [{}]" , principal . getId ( ) ) ; return principal . getId ( ) ; } else { LOGGER . debug ( "CAS will NOT be using the identifier from the resolved principal [{}] as it's not " + "configured to use the currently-resolved principal id and will fall back onto using the identifier " + "for the credential, that is [{}], for principal resolution" , principal , id ) ; } } else { LOGGER . debug ( "No principal is currently resolved and available. Falling back onto using the identifier " + " for the credential, that is [{}], for principal resolution" , id ) ; } LOGGER . debug ( "Extracted principal id [{}]" , id ) ; return id ; }
Extracts the id of the user from the provided credential . This method should be overridden by subclasses to achieve more sophisticated strategies for producing a principal ID from a credential .
17,792
protected boolean doPrincipalAttributesAllowSurrogateServiceAccess ( final Map < String , Object > principalAttributes ) { if ( ! enoughRequiredAttributesAvailableToProcess ( principalAttributes , this . surrogateRequiredAttributes ) ) { LOGGER . debug ( "Surrogate access is denied. There are not enough attributes available to satisfy the requirements [{}]" , this . surrogateRequiredAttributes ) ; return false ; } if ( ! doRequiredAttributesAllowPrincipalAccess ( principalAttributes , this . surrogateRequiredAttributes ) ) { LOGGER . debug ( "Surrogate access is denied. The principal does not have the required attributes [{}] specified by this strategy" , this . surrogateRequiredAttributes ) ; return false ; } return true ; }
Do principal attributes allow surrogate service access? .
17,793
protected JsonWebSignature createJsonWebSignature ( final JwtClaims claims ) { val jws = new JsonWebSignature ( ) ; val jsonClaims = claims . toJson ( ) ; jws . setPayload ( jsonClaims ) ; jws . setAlgorithmHeaderValue ( AlgorithmIdentifiers . NONE ) ; jws . setAlgorithmConstraints ( AlgorithmConstraints . NO_CONSTRAINTS ) ; return jws ; }
Gets json web signature .
17,794
protected String encryptToken ( final String encryptionAlg , final String encryptionEncoding , final String keyIdHeaderValue , final Key publicKey , final String payload ) { val jwe = new JsonWebEncryption ( ) ; jwe . setAlgorithmHeaderValue ( encryptionAlg ) ; jwe . setEncryptionMethodHeaderParameter ( encryptionEncoding ) ; jwe . setKey ( publicKey ) ; jwe . setKeyIdHeaderValue ( keyIdHeaderValue ) ; jwe . setContentTypeHeaderValue ( "JWT" ) ; jwe . setPayload ( payload ) ; return jwe . getCompactSerialization ( ) ; }
Create json web encryption json web encryption .
17,795
protected JsonWebSignature configureJsonWebSignatureForTokenSigning ( final OAuthRegisteredService svc , final JsonWebSignature jws , final PublicJsonWebKey jsonWebKey ) { LOGGER . debug ( "Service [{}] is set to sign id tokens" , svc ) ; jws . setKey ( jsonWebKey . getPrivateKey ( ) ) ; jws . setAlgorithmConstraints ( AlgorithmConstraints . DISALLOW_NONE ) ; if ( StringUtils . isNotBlank ( jsonWebKey . getKeyId ( ) ) ) { jws . setKeyIdHeaderValue ( jsonWebKey . getKeyId ( ) ) ; } LOGGER . debug ( "Signing id token with key id header value [{}]" , jws . getKeyIdHeaderValue ( ) ) ; jws . setAlgorithmHeaderValue ( getJsonWebKeySigningAlgorithm ( svc ) ) ; LOGGER . debug ( "Signing id token with algorithm [{}]" , jws . getAlgorithmHeaderValue ( ) ) ; return jws ; }
Configure json web signature for id token signing .
17,796
protected ModelAndView buildCallbackViewViaRedirectUri ( final J2EContext context , final String clientId , final Authentication authentication , final OAuthCode code ) { val attributes = authentication . getAttributes ( ) ; val state = attributes . get ( OAuth20Constants . STATE ) . get ( 0 ) . toString ( ) ; val nonce = attributes . get ( OAuth20Constants . NONCE ) . get ( 0 ) . toString ( ) ; val redirectUri = context . getRequestParameter ( OAuth20Constants . REDIRECT_URI ) ; LOGGER . debug ( "Authorize request verification successful for client [{}] with redirect uri [{}]" , clientId , redirectUri ) ; var callbackUrl = redirectUri ; callbackUrl = CommonHelper . addParameter ( callbackUrl , OAuth20Constants . CODE , code . getId ( ) ) ; if ( StringUtils . isNotBlank ( state ) ) { callbackUrl = CommonHelper . addParameter ( callbackUrl , OAuth20Constants . STATE , state ) ; } if ( StringUtils . isNotBlank ( nonce ) ) { callbackUrl = CommonHelper . addParameter ( callbackUrl , OAuth20Constants . NONCE , nonce ) ; } LOGGER . debug ( "Redirecting to URL [{}]" , callbackUrl ) ; val params = new LinkedHashMap < String , String > ( ) ; params . put ( OAuth20Constants . CODE , code . getId ( ) ) ; params . put ( OAuth20Constants . STATE , state ) ; params . put ( OAuth20Constants . NONCE , nonce ) ; params . put ( OAuth20Constants . CLIENT_ID , clientId ) ; return buildResponseModelAndView ( context , servicesManager , clientId , callbackUrl , params ) ; }
Build callback view via redirect uri model and view .
17,797
public static String encodeBase64 ( final String data ) { return Base64 . encodeBase64String ( data . getBytes ( StandardCharsets . UTF_8 ) ) ; }
Base64 - encode the given string as a string .
17,798
public static String urlEncode ( final String value , final String encoding ) { return URLEncoder . encode ( value , encoding ) ; }
Url encode a value .
17,799
public static String urlDecode ( final String value ) { return URLDecoder . decode ( value , StandardCharsets . UTF_8 . name ( ) ) ; }
Url decode a value .