idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
17,500
public static Pattern createPattern ( final String pattern , final int flags ) { if ( pattern == null ) { LOGGER . debug ( "Pattern cannot be null" ) ; return MATCH_NOTHING_PATTERN ; } try { return Pattern . compile ( pattern , flags ) ; } catch ( final PatternSyntaxException exception ) { LOGGER . debug ( "Pattern [{}] is not a valid regex." , pattern ) ; return MATCH_NOTHING_PATTERN ; } }
Creates the pattern with the given flags .
17,501
public static boolean matches ( final Pattern pattern , final String value , final boolean completeMatch ) { val matcher = pattern . matcher ( value ) ; LOGGER . debug ( "Matching value [{}] against pattern [{}]" , value , pattern . pattern ( ) ) ; if ( completeMatch ) { return matcher . matches ( ) ; } return matcher . find ( ) ; }
Matches boolean .
17,502
public static boolean find ( final String pattern , final String string ) { return createPattern ( pattern , Pattern . CASE_INSENSITIVE ) . matcher ( string ) . find ( ) ; }
Attempts to find the next sub - sequence of the input sequence that matches the pattern .
17,503
private static void verifyRegisteredServiceProperties ( final RegisteredService registeredService , final Service service ) { if ( registeredService == null ) { val msg = String . format ( "Service [%s] is not found in service registry." , service . getId ( ) ) ; LOGGER . warn ( msg ) ; throw new UnauthorizedServiceException ( UnauthorizedServiceException . CODE_UNAUTHZ_SERVICE , msg ) ; } if ( ! registeredService . getAccessStrategy ( ) . isServiceAccessAllowed ( ) ) { val msg = String . format ( "ServiceManagement: Unauthorized Service Access. " + "Service [%s] is not enabled in service registry." , service . getId ( ) ) ; LOGGER . warn ( msg ) ; throw new UnauthorizedServiceException ( UnauthorizedServiceException . CODE_UNAUTHZ_SERVICE , msg ) ; } }
Ensure that the service is found and enabled in the service registry .
17,504
protected Credential getServiceCredentialsFromRequest ( final WebApplicationService service , final HttpServletRequest request ) { val pgtUrl = request . getParameter ( CasProtocolConstants . PARAMETER_PROXY_CALLBACK_URL ) ; if ( StringUtils . isNotBlank ( pgtUrl ) ) { try { val registeredService = serviceValidateConfigurationContext . getServicesManager ( ) . findServiceBy ( service ) ; verifyRegisteredServiceProperties ( registeredService , service ) ; return new HttpBasedServiceCredential ( new URL ( pgtUrl ) , registeredService ) ; } catch ( final Exception e ) { LOGGER . error ( "Error constructing [{}]" , CasProtocolConstants . PARAMETER_PROXY_CALLBACK_URL , e ) ; } } return null ; }
Overrideable method to determine which credentials to use to grant a proxy granting ticket . Default is to use the pgtUrl .
17,505
protected void initBinder ( final HttpServletRequest request , final ServletRequestDataBinder binder ) { if ( serviceValidateConfigurationContext . isRenewEnabled ( ) ) { binder . setRequiredFields ( CasProtocolConstants . PARAMETER_RENEW ) ; } }
Initialize the binder with the required fields .
17,506
public TicketGrantingTicket handleProxyGrantingTicketDelivery ( final String serviceTicketId , final Credential credential ) throws AuthenticationException , AbstractTicketException { val serviceTicket = serviceValidateConfigurationContext . getCentralAuthenticationService ( ) . getTicket ( serviceTicketId , ServiceTicket . class ) ; val authenticationResult = serviceValidateConfigurationContext . getAuthenticationSystemSupport ( ) . handleAndFinalizeSingleAuthenticationTransaction ( serviceTicket . getService ( ) , credential ) ; val proxyGrantingTicketId = serviceValidateConfigurationContext . getCentralAuthenticationService ( ) . createProxyGrantingTicket ( serviceTicketId , authenticationResult ) ; LOGGER . debug ( "Generated proxy-granting ticket [{}] off of service ticket [{}] and credential [{}]" , proxyGrantingTicketId . getId ( ) , serviceTicketId , credential ) ; return proxyGrantingTicketId ; }
Handle proxy granting ticket delivery .
17,507
protected ModelAndView handleTicketValidation ( final HttpServletRequest request , final WebApplicationService service , final String serviceTicketId ) { var proxyGrantingTicketId = ( TicketGrantingTicket ) null ; val serviceCredential = getServiceCredentialsFromRequest ( service , request ) ; if ( serviceCredential != null ) { try { proxyGrantingTicketId = handleProxyGrantingTicketDelivery ( serviceTicketId , serviceCredential ) ; } catch ( final AuthenticationException e ) { LOGGER . warn ( "Failed to authenticate service credential [{}]" , serviceCredential ) ; return generateErrorView ( CasProtocolConstants . ERROR_CODE_INVALID_PROXY_CALLBACK , new Object [ ] { serviceCredential . getId ( ) } , request , service ) ; } catch ( final InvalidTicketException e ) { LOGGER . error ( "Failed to create proxy granting ticket due to an invalid ticket for [{}]" , serviceCredential , e ) ; return generateErrorView ( e . getCode ( ) , new Object [ ] { serviceTicketId } , request , service ) ; } catch ( final AbstractTicketException e ) { LOGGER . error ( "Failed to create proxy granting ticket for [{}]" , serviceCredential , e ) ; return generateErrorView ( e . getCode ( ) , new Object [ ] { serviceCredential . getId ( ) } , request , service ) ; } } val assertion = validateServiceTicket ( service , serviceTicketId ) ; if ( ! validateAssertion ( request , serviceTicketId , assertion , service ) ) { return generateErrorView ( CasProtocolConstants . ERROR_CODE_INVALID_TICKET , new Object [ ] { serviceTicketId } , request , service ) ; } val ctxResult = serviceValidateConfigurationContext . getRequestedContextValidator ( ) . validateAuthenticationContext ( assertion , request ) ; if ( ! ctxResult . getKey ( ) ) { throw new UnsatisfiedAuthenticationContextTicketValidationException ( assertion . getService ( ) ) ; } var proxyIou = StringUtils . EMPTY ; val proxyHandler = serviceValidateConfigurationContext . getProxyHandler ( ) ; if ( serviceCredential != null && proxyHandler != null && proxyHandler . canHandle ( serviceCredential ) ) { proxyIou = handleProxyIouDelivery ( serviceCredential , proxyGrantingTicketId ) ; if ( StringUtils . isEmpty ( proxyIou ) ) { return generateErrorView ( CasProtocolConstants . ERROR_CODE_INVALID_PROXY_CALLBACK , new Object [ ] { serviceCredential . getId ( ) } , request , service ) ; } } else { LOGGER . debug ( "No service credentials specified, and/or the proxy handler [{}] cannot handle credentials" , proxyHandler ) ; } onSuccessfulValidation ( serviceTicketId , assertion ) ; LOGGER . debug ( "Successfully validated service ticket [{}] for service [{}]" , serviceTicketId , service . getId ( ) ) ; return generateSuccessView ( assertion , proxyIou , service , request , ctxResult . getValue ( ) , proxyGrantingTicketId ) ; }
Handle ticket validation model and view .
17,508
protected Assertion validateServiceTicket ( final WebApplicationService service , final String serviceTicketId ) { return serviceValidateConfigurationContext . getCentralAuthenticationService ( ) . validateServiceTicket ( serviceTicketId , service ) ; }
Validate service ticket assertion .
17,509
private boolean validateAssertion ( final HttpServletRequest request , final String serviceTicketId , final Assertion assertion , final Service service ) { for ( val spec : serviceValidateConfigurationContext . getValidationSpecifications ( ) ) { spec . reset ( ) ; val binder = new ServletRequestDataBinder ( spec , "validationSpecification" ) ; initBinder ( request , binder ) ; binder . bind ( request ) ; if ( ! spec . isSatisfiedBy ( assertion , request ) ) { LOGGER . warn ( "Service ticket [{}] does not satisfy validation specification." , serviceTicketId ) ; return false ; } } enforceTicketValidationAuthorizationFor ( request , service , assertion ) ; return true ; }
Validate assertion .
17,510
private ModelAndView generateErrorView ( final String code , final Object [ ] args , final HttpServletRequest request , final WebApplicationService service ) { val modelAndView = serviceValidateConfigurationContext . getValidationViewFactory ( ) . getModelAndView ( request , false , service , getClass ( ) ) ; val convertedDescription = this . applicationContext . getMessage ( code , args , code , request . getLocale ( ) ) ; modelAndView . addObject ( CasViewConstants . MODEL_ATTRIBUTE_NAME_ERROR_CODE , StringEscapeUtils . escapeHtml4 ( code ) ) ; modelAndView . addObject ( CasViewConstants . MODEL_ATTRIBUTE_NAME_ERROR_DESCRIPTION , StringEscapeUtils . escapeHtml4 ( convertedDescription ) ) ; return modelAndView ; }
Generate error view .
17,511
private ModelAndView generateSuccessView ( final Assertion assertion , final String proxyIou , final WebApplicationService service , final HttpServletRequest request , final Optional < MultifactorAuthenticationProvider > contextProvider , final TicketGrantingTicket proxyGrantingTicket ) { val modelAndView = serviceValidateConfigurationContext . getValidationViewFactory ( ) . getModelAndView ( request , true , service , getClass ( ) ) ; modelAndView . addObject ( CasViewConstants . MODEL_ATTRIBUTE_NAME_ASSERTION , assertion ) ; modelAndView . addObject ( CasViewConstants . MODEL_ATTRIBUTE_NAME_SERVICE , service ) ; if ( StringUtils . isNotBlank ( proxyIou ) ) { modelAndView . addObject ( CasViewConstants . MODEL_ATTRIBUTE_NAME_PROXY_GRANTING_TICKET_IOU , proxyIou ) ; } if ( proxyGrantingTicket != null ) { modelAndView . addObject ( CasViewConstants . MODEL_ATTRIBUTE_NAME_PROXY_GRANTING_TICKET , proxyGrantingTicket . getId ( ) ) ; } contextProvider . ifPresent ( provider -> modelAndView . addObject ( serviceValidateConfigurationContext . getAuthnContextAttribute ( ) , provider . getId ( ) ) ) ; val augmentedModelObjects = augmentSuccessViewModelObjects ( assertion ) ; modelAndView . addAllObjects ( augmentedModelObjects ) ; return modelAndView ; }
Generate the success view . The result will contain the assertion and the proxy iou .
17,512
protected void enforceTicketValidationAuthorizationFor ( final HttpServletRequest request , final Service service , final Assertion assertion ) { val authorizers = serviceValidateConfigurationContext . getValidationAuthorizers ( ) . getAuthorizers ( ) ; for ( val a : authorizers ) { try { a . authorize ( request , service , assertion ) ; } catch ( final Exception e ) { throw new UnauthorizedServiceTicketValidationException ( service ) ; } } }
Enforce ticket validation authorization for .
17,513
private static int getTimeToLive ( final Ticket ticket ) { val expTime = ticket . getExpirationPolicy ( ) . getTimeToLive ( ) . intValue ( ) ; if ( TimeUnit . SECONDS . toDays ( expTime ) >= MAX_EXP_TIME_IN_DAYS ) { LOGGER . warn ( "Any expiration time larger than [{}] days in seconds is considered absolute (as in a Unix time stamp) " + "anything smaller is considered relative in seconds." , MAX_EXP_TIME_IN_DAYS ) ; } return expTime ; }
Get the expiration policy value of the ticket in seconds .
17,514
protected int deleteChildren ( final TicketGrantingTicket ticket ) { val count = new AtomicInteger ( 0 ) ; val services = ticket . getServices ( ) ; if ( services != null && ! services . isEmpty ( ) ) { services . keySet ( ) . forEach ( ticketId -> { if ( deleteSingleTicket ( ticketId ) ) { LOGGER . debug ( "Removed ticket [{}]" , ticketId ) ; count . incrementAndGet ( ) ; } else { LOGGER . debug ( "Unable to remove ticket [{}]" , ticketId ) ; } } ) ; } return count . intValue ( ) ; }
Delete TGT s service tickets .
17,515
protected String encodeTicketId ( final String ticketId ) { if ( ! isCipherExecutorEnabled ( ) ) { LOGGER . trace ( MESSAGE ) ; return ticketId ; } if ( StringUtils . isBlank ( ticketId ) ) { return ticketId ; } val encodedId = DigestUtils . sha512 ( ticketId ) ; LOGGER . debug ( "Encoded original ticket id [{}] to [{}]" , ticketId , encodedId ) ; return encodedId ; }
Encode ticket id into a SHA - 512 .
17,516
protected Ticket encodeTicket ( final Ticket ticket ) { if ( ! isCipherExecutorEnabled ( ) ) { LOGGER . trace ( MESSAGE ) ; return ticket ; } if ( ticket == null ) { LOGGER . debug ( "Ticket passed is null and cannot be encoded" ) ; return null ; } LOGGER . debug ( "Encoding ticket [{}]" , ticket ) ; val encodedTicketObject = SerializationUtils . serializeAndEncodeObject ( this . cipherExecutor , ticket ) ; val encodedTicketId = encodeTicketId ( ticket . getId ( ) ) ; val encodedTicket = new EncodedTicket ( encodedTicketId , ByteSource . wrap ( encodedTicketObject ) . read ( ) ) ; LOGGER . debug ( "Created encoded ticket [{}]" , encodedTicket ) ; return encodedTicket ; }
Encode ticket .
17,517
protected Ticket decodeTicket ( final Ticket result ) { if ( ! isCipherExecutorEnabled ( ) ) { LOGGER . trace ( MESSAGE ) ; return result ; } if ( result == null ) { LOGGER . warn ( "Ticket passed is null and cannot be decoded" ) ; return null ; } if ( ! result . getClass ( ) . isAssignableFrom ( EncodedTicket . class ) ) { LOGGER . warn ( "Ticket passed is not an encoded ticket type; rather it's a [{}], no decoding is necessary." , result . getClass ( ) . getSimpleName ( ) ) ; return result ; } LOGGER . debug ( "Attempting to decode [{}]" , result ) ; val encodedTicket = ( EncodedTicket ) result ; val ticket = SerializationUtils . decodeAndDeserializeObject ( encodedTicket . getEncodedTicket ( ) , this . cipherExecutor , Ticket . class ) ; LOGGER . debug ( "Decoded ticket to [{}]" , ticket ) ; return ticket ; }
Decode ticket .
17,518
protected Map < String , List < Object > > getPrincipalAttributesForPrincipal ( final Principal principal , final Map < String , List < Object > > principalAttributes ) { return principalAttributes ; }
Gets principal attributes for principal .
17,519
private List < Resource > scanForConfigurationResources ( final File config , final List < String > profiles ) { val possibleFiles = getAllPossibleExternalConfigDirFilenames ( config , profiles ) ; return possibleFiles . stream ( ) . filter ( File :: exists ) . filter ( File :: isFile ) . map ( FileSystemResource :: new ) . collect ( Collectors . toList ( ) ) ; }
Get all possible configuration files for config directory that actually exist as files .
17,520
private PropertySource < ? > loadSettingsByApplicationProfiles ( final Environment environment , final File config ) { val profiles = ConfigurationPropertiesLoaderFactory . getApplicationProfiles ( environment ) ; val resources = scanForConfigurationResources ( config , profiles ) ; val composite = new CompositePropertySource ( "applicationProfilesCompositeProperties" ) ; LOGGER . info ( "Configuration files found at [{}] are [{}] under profile(s) [{}]" , config , resources , profiles ) ; resources . forEach ( Unchecked . consumer ( f -> { LOGGER . debug ( "Loading configuration file [{}]" , f ) ; val loader = configurationPropertiesLoaderFactory . getLoader ( f , "applicationProfilesProperties-" + f . getFilename ( ) ) ; composite . addFirstPropertySource ( loader . load ( ) ) ; } ) ) ; return composite ; }
Property files processed in order of non - profiles first and then profiles and profiles are first to last with properties in the last profile overriding properties in previous profiles or non - profiles .
17,521
protected void handleUnmappedAttribute ( final Map < String , List < Object > > attributesToRelease , final String attributeName , final Object attributeValue ) { LOGGER . debug ( "Found attribute [{}] that is not defined in pattern definitions" , attributeName ) ; if ( excludeUnmappedAttributes ) { LOGGER . debug ( "Excluding attribute [{}] given unmatched attributes are to be excluded" , attributeName ) ; } else { LOGGER . debug ( "Added unmatched attribute [{}] with value(s) [{}]" , attributeName , attributeValue ) ; attributesToRelease . put ( attributeName , CollectionUtils . toCollection ( attributeValue , ArrayList . class ) ) ; } }
Handle unmapped attribute .
17,522
protected Collection < Pattern > createPatternForMappedAttribute ( final String attributeName ) { val matchingPattern = patterns . get ( attributeName ) . toString ( ) ; val pattern = RegexUtils . createPattern ( matchingPattern , this . caseInsensitive ? Pattern . CASE_INSENSITIVE : 0 ) ; LOGGER . debug ( "Created pattern for mapped attribute filter [{}]" , pattern . pattern ( ) ) ; return CollectionUtils . wrap ( pattern ) ; }
Create pattern for mapped attribute pattern .
17,523
protected void collectAttributeWithFilteredValues ( final Map < String , List < Object > > attributesToRelease , final String attributeName , final List < Object > filteredValues ) { attributesToRelease . put ( attributeName , filteredValues ) ; }
Collect attribute with filtered values .
17,524
protected Predicate < Map . Entry < String , List < Object > > > filterProvidedGivenAttributes ( ) { return entry -> { val attributeName = entry . getKey ( ) ; val attributeValue = entry . getValue ( ) ; LOGGER . debug ( "Received attribute [{}] with value(s) [{}]" , attributeName , attributeValue ) ; return attributeValue != null ; } ; }
Filter provided given attributes predicate .
17,525
protected List < Object > filterAttributeValuesByPattern ( final Set < Object > attributeValues , final Pattern pattern ) { return attributeValues . stream ( ) . filter ( v -> RegexUtils . matches ( pattern , v . toString ( ) , completeMatch ) ) . collect ( Collectors . toList ( ) ) ; }
Filter attribute values by pattern and return the list .
17,526
public AmazonDynamoDB createAmazonDynamoDb ( final AbstractDynamoDbProperties props ) { if ( props . isLocalInstance ( ) ) { LOGGER . debug ( "Creating DynamoDb standard client with endpoint [{}] and region [{}]" , props . getEndpoint ( ) , props . getRegion ( ) ) ; val endpoint = new AwsClientBuilder . EndpointConfiguration ( props . getEndpoint ( ) , props . getRegion ( ) ) ; return AmazonDynamoDBClientBuilder . standard ( ) . withEndpointConfiguration ( endpoint ) . build ( ) ; } val provider = ChainingAWSCredentialsProvider . getInstance ( props . getCredentialAccessKey ( ) , props . getCredentialSecretKey ( ) , props . getCredentialsPropertiesFile ( ) ) ; LOGGER . trace ( "Creating DynamoDb client configuration..." ) ; val cfg = AmazonClientConfigurationBuilder . buildClientConfiguration ( props ) ; LOGGER . debug ( "Creating DynamoDb client instance..." ) ; val clientBuilder = AmazonDynamoDBClientBuilder . standard ( ) . withClientConfiguration ( cfg ) . withCredentials ( provider ) ; val region = StringUtils . defaultIfBlank ( props . getRegionOverride ( ) , props . getRegion ( ) ) ; if ( StringUtils . isNotBlank ( props . getEndpoint ( ) ) ) { LOGGER . trace ( "Setting DynamoDb client endpoint [{}]" , props . getEndpoint ( ) ) ; clientBuilder . withEndpointConfiguration ( new AwsClientBuilder . EndpointConfiguration ( props . getEndpoint ( ) , region ) ) ; } if ( StringUtils . isNotBlank ( region ) ) { LOGGER . trace ( "Setting DynamoDb client region [{}]" , props . getRegion ( ) ) ; clientBuilder . withRegion ( region ) ; } return clientBuilder . build ( ) ; }
Create amazon dynamo db instance .
17,527
public static ModelAndView writeError ( final HttpServletResponse response , final String error ) { val model = CollectionUtils . wrap ( OAuth20Constants . ERROR , error ) ; val mv = new ModelAndView ( new MappingJackson2JsonView ( MAPPER ) , ( Map ) model ) ; mv . setStatus ( HttpStatus . BAD_REQUEST ) ; response . setStatus ( HttpStatus . BAD_REQUEST . value ( ) ) ; return mv ; }
Write to the output this error .
17,528
public static OAuthRegisteredService getRegisteredOAuthServiceByRedirectUri ( final ServicesManager servicesManager , final String redirectUri ) { return getRegisteredOAuthServiceByPredicate ( servicesManager , s -> s . matches ( redirectUri ) ) ; }
Gets registered oauth service by redirect uri .
17,529
public static Map < String , Object > getRequestParameters ( final Collection < String > attributes , final HttpServletRequest context ) { return attributes . stream ( ) . filter ( a -> StringUtils . isNotBlank ( context . getParameter ( a ) ) ) . map ( m -> { val values = context . getParameterValues ( m ) ; val valuesSet = new LinkedHashSet < Object > ( ) ; if ( values != null && values . length > 0 ) { Arrays . stream ( values ) . forEach ( v -> valuesSet . addAll ( Arrays . stream ( v . split ( " " ) ) . collect ( Collectors . toSet ( ) ) ) ) ; } return Pair . of ( m , valuesSet ) ; } ) . collect ( Collectors . toMap ( Pair :: getKey , Pair :: getValue ) ) ; }
Gets attributes .
17,530
public static Collection < String > getRequestedScopes ( final HttpServletRequest context ) { val map = getRequestParameters ( CollectionUtils . wrap ( OAuth20Constants . SCOPE ) , context ) ; if ( map == null || map . isEmpty ( ) ) { return new ArrayList < > ( 0 ) ; } return ( Collection < String > ) map . get ( OAuth20Constants . SCOPE ) ; }
Gets requested scopes .
17,531
public static String casOAuthCallbackUrl ( final String serverPrefixUrl ) { return serverPrefixUrl . concat ( OAuth20Constants . BASE_OAUTH20_URL + '/' + OAuth20Constants . CALLBACK_AUTHORIZE_URL ) ; }
CAS oauth callback url .
17,532
public static boolean isResponseModeTypeFormPost ( final OAuthRegisteredService registeredService , final OAuth20ResponseModeTypes responseType ) { return responseType == OAuth20ResponseModeTypes . FORM_POST || StringUtils . equalsIgnoreCase ( "post" , registeredService . getResponseType ( ) ) ; }
Is response mode type form post?
17,533
public static OAuth20ResponseTypes getResponseType ( final J2EContext context ) { val responseType = context . getRequestParameter ( OAuth20Constants . RESPONSE_TYPE ) ; val type = Arrays . stream ( OAuth20ResponseTypes . values ( ) ) . filter ( t -> t . getType ( ) . equalsIgnoreCase ( responseType ) ) . findFirst ( ) . orElse ( OAuth20ResponseTypes . CODE ) ; LOGGER . debug ( "OAuth response type is [{}]" , type ) ; return type ; }
Gets response type .
17,534
public static OAuth20ResponseModeTypes getResponseModeType ( final J2EContext context ) { val responseType = context . getRequestParameter ( OAuth20Constants . RESPONSE_MODE ) ; val type = Arrays . stream ( OAuth20ResponseModeTypes . values ( ) ) . filter ( t -> t . getType ( ) . equalsIgnoreCase ( responseType ) ) . findFirst ( ) . orElse ( OAuth20ResponseModeTypes . NONE ) ; LOGGER . debug ( "OAuth response type is [{}]" , type ) ; return type ; }
Gets response mode type .
17,535
public static boolean isAuthorizedResponseTypeForService ( final J2EContext context , final OAuthRegisteredService registeredService ) { val responseType = context . getRequestParameter ( OAuth20Constants . RESPONSE_TYPE ) ; if ( registeredService . getSupportedResponseTypes ( ) != null && ! registeredService . getSupportedResponseTypes ( ) . isEmpty ( ) ) { LOGGER . debug ( "Checking response type [{}] against supported response types [{}]" , responseType , registeredService . getSupportedResponseTypes ( ) ) ; return registeredService . getSupportedResponseTypes ( ) . stream ( ) . anyMatch ( s -> s . equalsIgnoreCase ( responseType ) ) ; } LOGGER . warn ( "Registered service [{}] does not define any authorized/supported response types. " + "It is STRONGLY recommended that you authorize and assign response types to the service definition. " + "While just a warning for now, this behavior will be enforced by CAS in future versions." , registeredService . getName ( ) ) ; return true ; }
Is authorized response type for service?
17,536
public static Set < String > parseRequestScopes ( final HttpServletRequest context ) { val parameterValues = context . getParameter ( OAuth20Constants . SCOPE ) ; if ( StringUtils . isBlank ( parameterValues ) ) { return new HashSet < > ( 0 ) ; } return CollectionUtils . wrapSet ( parameterValues . split ( " " ) ) ; }
Parse request scopes set .
17,537
public static String getServiceRequestHeaderIfAny ( final HttpServletRequest context ) { if ( context == null ) { return null ; } var id = context . getHeader ( CasProtocolConstants . PARAMETER_SERVICE ) ; if ( StringUtils . isBlank ( id ) ) { id = context . getHeader ( "X-" . concat ( CasProtocolConstants . PARAMETER_SERVICE ) ) ; } return id ; }
Gets service request header if any .
17,538
public static boolean checkCallbackValid ( final RegisteredService registeredService , final String redirectUri ) { val registeredServiceId = registeredService . getServiceId ( ) ; LOGGER . debug ( "Found: [{}] vs redirectUri: [{}]" , registeredService , redirectUri ) ; if ( ! redirectUri . matches ( registeredServiceId ) ) { LOGGER . error ( "Unsupported [{}]: [{}] does not match what is defined for registered service: [{}]. " + "Service is considered unauthorized. Verify the service definition in the registry is correct " + "and does in fact match the client [{}]" , OAuth20Constants . REDIRECT_URI , redirectUri , registeredServiceId , redirectUri ) ; return false ; } return true ; }
Check if the callback url is valid .
17,539
public static boolean checkClientSecret ( final OAuthRegisteredService registeredService , final String clientSecret ) { LOGGER . debug ( "Found: [{}] in secret check" , registeredService ) ; if ( StringUtils . isBlank ( registeredService . getClientSecret ( ) ) ) { LOGGER . debug ( "The client secret is not defined for the registered service [{}]" , registeredService . getName ( ) ) ; return true ; } if ( ! StringUtils . equals ( registeredService . getClientSecret ( ) , clientSecret ) ) { LOGGER . error ( "Wrong client secret for service: [{}]" , registeredService . getServiceId ( ) ) ; return false ; } return true ; }
Check the client secret .
17,540
public static boolean checkResponseTypes ( final String type , final OAuth20ResponseTypes ... expectedTypes ) { LOGGER . debug ( "Response type: [{}]" , type ) ; val checked = Stream . of ( expectedTypes ) . anyMatch ( t -> OAuth20Utils . isResponseType ( type , t ) ) ; if ( ! checked ) { LOGGER . error ( "Unsupported response type: [{}]" , type ) ; } return checked ; }
Check the response type against expected response types .
17,541
public static String getClientIdFromAuthenticatedProfile ( final CommonProfile profile ) { if ( profile . containsAttribute ( OAuth20Constants . CLIENT_ID ) ) { val attribute = profile . getAttribute ( OAuth20Constants . CLIENT_ID ) ; return CollectionUtils . toCollection ( attribute , ArrayList . class ) . get ( 0 ) . toString ( ) ; } return null ; }
Gets client id from authenticated profile .
17,542
public static WSFederationRequest of ( final HttpServletRequest request ) { val wtrealm = request . getParameter ( WSFederationConstants . WTREALM ) ; val wreply = request . getParameter ( WSFederationConstants . WREPLY ) ; val wreq = request . getParameter ( WSFederationConstants . WREQ ) ; val wctx = request . getParameter ( WSFederationConstants . WCTX ) ; val wfresh = request . getParameter ( WSFederationConstants . WREFRESH ) ; val whr = request . getParameter ( WSFederationConstants . WHR ) ; val wresult = request . getParameter ( WSFederationConstants . WRESULT ) ; val relayState = request . getParameter ( WSFederationConstants . RELAY_STATE ) ; val samlResponse = request . getParameter ( WSFederationConstants . SAML_RESPONSE ) ; val state = request . getParameter ( WSFederationConstants . STATE ) ; val code = request . getParameter ( WSFederationConstants . CODE ) ; val wa = request . getParameter ( WSFederationConstants . WA ) ; val wauth = StringUtils . defaultIfBlank ( request . getParameter ( WSFederationConstants . WAUTH ) , "default" ) ; return new WSFederationRequest ( wtrealm , wreply , wctx , wfresh , whr , wresult , relayState , samlResponse , state , code , wa , wauth , wreq ) ; }
Create federation request .
17,543
private Stream < String > getKeysStream ( ) { val cursor = client . getConnectionFactory ( ) . getConnection ( ) . scan ( ScanOptions . scanOptions ( ) . match ( getPatternTicketRedisKey ( ) ) . count ( SCAN_COUNT ) . build ( ) ) ; return StreamSupport . stream ( Spliterators . spliteratorUnknownSize ( cursor , Spliterator . ORDERED ) , false ) . map ( key -> ( String ) client . getKeySerializer ( ) . deserialize ( key ) ) . collect ( Collectors . toSet ( ) ) . stream ( ) . onClose ( ( ) -> { try { cursor . close ( ) ; } catch ( final IOException e ) { LOGGER . error ( "Could not close Redis connection" , e ) ; } } ) ; }
Get a stream of all CAS - related keys from Redis DB .
17,544
protected Principal getAccessTokenAuthenticationPrincipal ( final AccessToken accessToken , final J2EContext context , final RegisteredService registeredService ) { val currentPrincipal = accessToken . getAuthentication ( ) . getPrincipal ( ) ; LOGGER . debug ( "Preparing user profile response based on CAS principal [{}]" , currentPrincipal ) ; val principal = this . scopeToAttributesFilter . filter ( accessToken . getService ( ) , currentPrincipal , registeredService , context , accessToken ) ; LOGGER . debug ( "Created CAS principal [{}] based on requested/authorized scopes" , principal ) ; return principal ; }
Gets access token authentication principal .
17,545
protected void finalizeProfileResponse ( final AccessToken accessTokenTicket , final Map < String , Object > map , final Principal principal ) { val service = accessTokenTicket . getService ( ) ; val registeredService = servicesManager . findServiceBy ( service ) ; if ( registeredService instanceof OAuthRegisteredService ) { val oauth = ( OAuthRegisteredService ) registeredService ; map . put ( OAuth20Constants . CLIENT_ID , oauth . getClientId ( ) ) ; map . put ( CasProtocolConstants . PARAMETER_SERVICE , service . getId ( ) ) ; } }
Finalize profile response .
17,546
public static Map loadYamlProperties ( final Resource ... resource ) { val factory = new YamlPropertiesFactoryBean ( ) ; factory . setResolutionMethod ( YamlProcessor . ResolutionMethod . OVERRIDE ) ; factory . setResources ( resource ) ; factory . setSingleton ( true ) ; factory . afterPropertiesSet ( ) ; return factory . getObject ( ) ; }
Load yaml properties map .
17,547
protected String grantServiceTicket ( final String ticketGrantingTicket , final Service service , final AuthenticationResult authenticationResult ) { val ticket = centralAuthenticationService . grantServiceTicket ( ticketGrantingTicket , service , authenticationResult ) ; LOGGER . debug ( "Generated service ticket [{}]" , ticket . getId ( ) ) ; return ticket . getId ( ) ; }
Grant service ticket service ticket .
17,548
protected CommonProfile buildUserProfile ( final TokenCredentials tokenCredentials , final WebContext webContext , final AccessToken accessToken ) { val userProfile = new CommonProfile ( true ) ; val authentication = accessToken . getAuthentication ( ) ; val principal = authentication . getPrincipal ( ) ; userProfile . setId ( principal . getId ( ) ) ; val attributes = new HashMap < String , Object > ( principal . getAttributes ( ) ) ; attributes . putAll ( authentication . getAttributes ( ) ) ; userProfile . addAttributes ( attributes ) ; LOGGER . trace ( "Built user profile based on access token [{}] is [{}]" , accessToken , userProfile ) ; return userProfile ; }
Build user profile common profile .
17,549
public View getView ( final HttpServletRequest request , final boolean isSuccess , final WebApplicationService service , final Class ownerClass ) { val type = getValidationResponseType ( request , service ) ; if ( type == ValidationResponseType . JSON ) { return getSingleInstanceView ( ServiceValidationViewTypes . JSON ) ; } return isSuccess ? getSuccessView ( ownerClass . getSimpleName ( ) ) : getFailureView ( ownerClass . getSimpleName ( ) ) ; }
Gets view .
17,550
public ModelAndView getModelAndView ( final HttpServletRequest request , final boolean isSuccess , final WebApplicationService service , final Class ownerClass ) { val view = getView ( request , isSuccess , service , ownerClass ) ; return new ModelAndView ( view ) ; }
Gets model and view .
17,551
private static ValidationResponseType getValidationResponseType ( final HttpServletRequest request , final WebApplicationService service ) { val format = request . getParameter ( CasProtocolConstants . PARAMETER_FORMAT ) ; final Function < String , ValidationResponseType > func = FunctionUtils . doIf ( StringUtils :: isNotBlank , t -> ValidationResponseType . valueOf ( t . toUpperCase ( ) ) , f -> service != null ? service . getFormat ( ) : ValidationResponseType . XML ) ; return func . apply ( format ) ; }
Gets validation response type .
17,552
public static LocalDateTime localDateTimeOf ( final String value ) { var result = ( LocalDateTime ) null ; try { result = LocalDateTime . parse ( value , DateTimeFormatter . ISO_LOCAL_DATE_TIME ) ; } catch ( final Exception e ) { result = null ; } if ( result == null ) { try { result = LocalDateTime . parse ( value , DateTimeFormatter . ISO_ZONED_DATE_TIME ) ; } catch ( final Exception e ) { result = null ; } } if ( result == null ) { try { result = LocalDateTime . parse ( value ) ; } catch ( final Exception e ) { result = null ; } } if ( result == null ) { try { result = LocalDateTime . parse ( value . toUpperCase ( ) , DateTimeFormatter . ofPattern ( "MM/dd/yyyy hh:mm a" ) ) ; } catch ( final Exception e ) { result = null ; } } if ( result == null ) { try { result = LocalDateTime . parse ( value . toUpperCase ( ) , DateTimeFormatter . ofPattern ( "MM/dd/yyyy h:mm a" ) ) ; } catch ( final Exception e ) { result = null ; } } if ( result == null ) { try { result = LocalDateTime . parse ( value , DateTimeFormatter . ofPattern ( "MM/dd/yyyy HH:mm" ) ) ; } catch ( final Exception e ) { result = null ; } } if ( result == null ) { try { val ld = LocalDate . parse ( value , DateTimeFormatter . ofPattern ( "MM/dd/yyyy" ) ) ; result = LocalDateTime . of ( ld , LocalTime . now ( ) ) ; } catch ( final Exception e ) { result = null ; } } if ( result == null ) { try { val ld = LocalDate . parse ( value ) ; result = LocalDateTime . of ( ld , LocalTime . now ( ) ) ; } catch ( final Exception e ) { result = null ; } } return result ; }
Parse the given value as a local datetime .
17,553
public static LocalDateTime localDateTimeOf ( final long time ) { return LocalDateTime . ofInstant ( Instant . ofEpochMilli ( time ) , ZoneId . systemDefault ( ) ) ; }
Local date time of local date time .
17,554
public static ZonedDateTime zonedDateTimeOf ( final String value ) { try { return ZonedDateTime . parse ( value ) ; } catch ( final Exception e ) { return null ; } }
Parse the given value as a zoned datetime .
17,555
public static ZonedDateTime zonedDateTimeOf ( final long time , final ZoneId zoneId ) { return ZonedDateTime . ofInstant ( Instant . ofEpochMilli ( time ) , zoneId ) ; }
Utility for creating a ZonedDateTime object from a millisecond timestamp .
17,556
public static ZonedDateTime zonedDateTimeOf ( final Calendar time ) { return ZonedDateTime . ofInstant ( time . toInstant ( ) , time . getTimeZone ( ) . toZoneId ( ) ) ; }
Gets ZonedDateTime for Calendar .
17,557
public static Date dateOf ( final LocalDate time ) { return Date . from ( time . atStartOfDay ( ZoneOffset . UTC ) . toInstant ( ) ) ; }
Date of local date .
17,558
public static ZonedDateTime convertToZonedDateTime ( final String value ) { val dt = DateTimeUtils . zonedDateTimeOf ( value ) ; if ( dt != null ) { return dt ; } val lt = DateTimeUtils . localDateTimeOf ( value ) ; return DateTimeUtils . zonedDateTimeOf ( lt . atZone ( ZoneOffset . UTC ) ) ; }
Convert to zoned date time .
17,559
public static TimeUnit toTimeUnit ( final ChronoUnit tu ) { if ( tu == null ) { return null ; } switch ( tu ) { case DAYS : return TimeUnit . DAYS ; case HOURS : return TimeUnit . HOURS ; case MINUTES : return TimeUnit . MINUTES ; case SECONDS : return TimeUnit . SECONDS ; case MICROS : return TimeUnit . MICROSECONDS ; case MILLIS : return TimeUnit . MILLISECONDS ; case NANOS : return TimeUnit . NANOSECONDS ; default : throw new UnsupportedOperationException ( "Temporal unit is not supported" ) ; } }
To time unit time unit .
17,560
protected boolean throttleRequest ( final HttpServletRequest request , final HttpServletResponse response ) { return configurationContext . getThrottledRequestExecutor ( ) != null && configurationContext . getThrottledRequestExecutor ( ) . throttle ( request , response ) ; }
Is request throttled .
17,561
protected boolean shouldResponseBeRecordedAsFailure ( final HttpServletResponse response ) { val status = response . getStatus ( ) ; return status != HttpStatus . SC_CREATED && status != HttpStatus . SC_OK && status != HttpStatus . SC_MOVED_TEMPORARILY ; }
Should response be recorded as failure boolean .
17,562
protected String getUsernameParameterFromRequest ( final HttpServletRequest request ) { return request . getParameter ( StringUtils . defaultString ( configurationContext . getUsernameParameter ( ) , "username" ) ) ; }
Construct username from the request .
17,563
protected Date getFailureInRangeCutOffDate ( ) { val cutoff = ZonedDateTime . now ( ZoneOffset . UTC ) . minusSeconds ( configurationContext . getFailureRangeInSeconds ( ) ) ; return DateTimeUtils . timestampOf ( cutoff ) ; }
Gets failure in range cut off date .
17,564
protected void recordAuditAction ( final HttpServletRequest request , final String actionName ) { val userToUse = getUsernameParameterFromRequest ( request ) ; val clientInfo = ClientInfoHolder . getClientInfo ( ) ; val resource = StringUtils . defaultString ( request . getParameter ( CasProtocolConstants . PARAMETER_SERVICE ) , "N/A" ) ; val context = new AuditActionContext ( userToUse , resource , actionName , configurationContext . getApplicationCode ( ) , DateTimeUtils . dateOf ( ZonedDateTime . now ( ZoneOffset . UTC ) ) , clientInfo . getClientIpAddress ( ) , clientInfo . getServerIpAddress ( ) ) ; LOGGER . debug ( "Recording throttled audit action [{}}" , context ) ; configurationContext . getAuditTrailExecutionPlan ( ) . record ( context ) ; }
Records an audit action .
17,565
private AuthnStatement buildAuthnStatement ( final Object casAssertion , final RequestAbstractType authnRequest , final SamlRegisteredServiceServiceProviderMetadataFacade adaptor , final SamlRegisteredService service , final String binding , final MessageContext messageContext , final HttpServletRequest request ) throws SamlException { val assertion = Assertion . class . cast ( casAssertion ) ; val authenticationMethod = this . authnContextClassRefBuilder . build ( assertion , authnRequest , adaptor , service ) ; var id = request != null ? CommonUtils . safeGetParameter ( request , CasProtocolConstants . PARAMETER_TICKET ) : StringUtils . EMPTY ; if ( StringUtils . isBlank ( id ) ) { LOGGER . warn ( "Unable to locate service ticket as the session index; Generating random identifier instead..." ) ; id = '_' + String . valueOf ( RandomUtils . nextLong ( ) ) ; } val statement = newAuthnStatement ( authenticationMethod , DateTimeUtils . zonedDateTimeOf ( assertion . getAuthenticationDate ( ) ) , id ) ; if ( assertion . getValidUntilDate ( ) != null ) { val dt = DateTimeUtils . zonedDateTimeOf ( assertion . getValidUntilDate ( ) ) ; statement . setSessionNotOnOrAfter ( DateTimeUtils . dateTimeOf ( dt . plusSeconds ( casProperties . getAuthn ( ) . getSamlIdp ( ) . getResponse ( ) . getSkewAllowance ( ) ) ) ) ; } val subjectLocality = buildSubjectLocality ( assertion , authnRequest , adaptor , binding ) ; statement . setSubjectLocality ( subjectLocality ) ; return statement ; }
Creates an authentication statement for the current request .
17,566
protected SubjectLocality buildSubjectLocality ( final Object assertion , final RequestAbstractType authnRequest , final SamlRegisteredServiceServiceProviderMetadataFacade adaptor , final String binding ) throws SamlException { val subjectLocality = newSamlObject ( SubjectLocality . class ) ; val hostAddress = InetAddressUtils . getCasServerHostAddress ( casProperties . getServer ( ) . getName ( ) ) ; val issuer = SamlIdPUtils . getIssuerFromSamlObject ( authnRequest ) ; LOGGER . debug ( "Built subject locality address [{}] for the saml authentication statement prepped for [{}]" , hostAddress , issuer ) ; subjectLocality . setAddress ( hostAddress ) ; return subjectLocality ; }
Build subject locality subject locality .
17,567
public CasServerProfile getProfile ( ) { val profile = new CasServerProfile ( ) ; profile . setRegisteredServiceTypesSupported ( locateRegisteredServiceTypesSupported ( ) ) ; profile . setRegisteredServiceTypes ( locateRegisteredServiceTypesActive ( ) ) ; profile . setMultifactorAuthenticationProviderTypesSupported ( locateMultifactorAuthenticationProviderTypesSupported ( ) ) ; profile . setMultifactorAuthenticationProviderTypes ( locateMultifactorAuthenticationProviderTypesActive ( ) ) ; profile . setDelegatedClientTypesSupported ( locateDelegatedClientTypesSupported ( ) ) ; profile . setDelegatedClientTypes ( locateDelegatedClientTypes ( ) ) ; profile . setAvailableAttributes ( this . availableAttributes ) ; return profile ; }
Gets profile .
17,568
public static org . apereo . cas . web . UrlValidator getInstance ( ) { if ( INSTANCE == null ) { INSTANCE = new SimpleUrlValidator ( UrlValidator . getInstance ( ) , DomainValidator . getInstance ( ) ) ; } return INSTANCE ; }
Gets a static instance to be used internal only .
17,569
public void handleApplicationReadyEvent ( final ApplicationReadyEvent event ) { AsciiArtUtils . printAsciiArtInfo ( LOGGER , "READY" , StringUtils . EMPTY ) ; LOGGER . info ( "Ready to process requests @ [{}]" , DateTimeUtils . zonedDateTimeOf ( event . getTimestamp ( ) ) ) ; }
Handle application ready event .
17,570
private static URI [ ] getDistributionPoints ( final X509Certificate cert ) { try { val points = new ExtensionReader ( cert ) . readCRLDistributionPoints ( ) ; val urls = new ArrayList < URI > ( ) ; if ( points != null ) { points . stream ( ) . map ( DistributionPoint :: getDistributionPoint ) . filter ( Objects :: nonNull ) . forEach ( pointName -> { val nameSequence = ASN1Sequence . getInstance ( pointName . getName ( ) ) ; IntStream . range ( 0 , nameSequence . size ( ) ) . mapToObj ( i -> GeneralName . getInstance ( nameSequence . getObjectAt ( i ) ) ) . forEach ( name -> { LOGGER . debug ( "Found CRL distribution point [{}]." , name ) ; try { addURL ( urls , DERIA5String . getInstance ( name . getName ( ) ) . getString ( ) ) ; } catch ( final Exception e ) { LOGGER . warn ( "[{}] not supported. String or GeneralNameList expected." , pointName ) ; } } ) ; } ) ; } return urls . toArray ( URI [ ] :: new ) ; } catch ( final Exception e ) { LOGGER . error ( "Error reading CRLDistributionPoints extension field on [{}]" , CertUtils . toString ( cert ) , e ) ; return new URI [ 0 ] ; } }
Gets the distribution points .
17,571
protected Event doExecute ( final RequestContext context ) { try { val request = WebUtils . getHttpServletRequestFromExternalWebflowContext ( context ) ; val wa = request . getParameter ( WA ) ; if ( StringUtils . isNotBlank ( wa ) && wa . equalsIgnoreCase ( WSIGNIN ) ) { wsFederationResponseValidator . validateWsFederationAuthenticationRequest ( context ) ; return super . doExecute ( context ) ; } return wsFederationRequestBuilder . buildAuthenticationRequestEvent ( context ) ; } catch ( final Exception ex ) { LOGGER . error ( ex . getMessage ( ) , ex ) ; throw new UnauthorizedServiceException ( UnauthorizedServiceException . CODE_UNAUTHZ_SERVICE , ex . getMessage ( ) ) ; } }
Executes the webflow action .
17,572
public boolean isValid ( ) { return StringUtils . isNotBlank ( getMetadata ( ) ) && StringUtils . isNotBlank ( getSigningCertificate ( ) ) && StringUtils . isNotBlank ( getSigningKey ( ) ) && StringUtils . isNotBlank ( getEncryptionCertificate ( ) ) && StringUtils . isNotBlank ( getEncryptionKey ( ) ) ; }
Is this document valid and has any of the fields?
17,573
public String getSigningCertificateDecoded ( ) { if ( EncodingUtils . isBase64 ( signingCertificate ) ) { return EncodingUtils . decodeBase64ToString ( signingCertificate ) ; } return signingCertificate ; }
Gets signing certificate decoded .
17,574
public String getEncryptionCertificateDecoded ( ) { if ( EncodingUtils . isBase64 ( encryptionCertificate ) ) { return EncodingUtils . decodeBase64ToString ( encryptionCertificate ) ; } return encryptionCertificate ; }
Gets encryption certificate decoded .
17,575
public String getMetadataDecoded ( ) { if ( EncodingUtils . isBase64 ( metadata ) ) { return EncodingUtils . decodeBase64ToString ( metadata ) ; } return metadata ; }
Gets metadata decoded .
17,576
protected ModelAndView handleRequestInternal ( final HttpServletRequest request , final HttpServletResponse response ) throws Exception { for ( val delegate : this . delegates ) { if ( delegate . canHandle ( request , response ) ) { return delegate . handleRequestInternal ( request , response ) ; } } return generateErrorView ( CasProtocolConstants . ERROR_CODE_INVALID_REQUEST , null ) ; }
Handles the request . Ask all delegates if they can handle the current request . The first to answer true is elected as the delegate that will process the request . If no controller answers true we redirect to the error page .
17,577
protected Assertion getAssertionFrom ( final Map < String , Object > model ) { return ( Assertion ) model . get ( CasViewConstants . MODEL_ATTRIBUTE_NAME_ASSERTION ) ; }
Gets the assertion from the model .
17,578
protected String getErrorCodeFrom ( final Map < String , Object > model ) { return model . get ( CasViewConstants . MODEL_ATTRIBUTE_NAME_ERROR_CODE ) . toString ( ) ; }
Gets error code from .
17,579
protected String getErrorDescriptionFrom ( final Map < String , Object > model ) { return model . get ( CasViewConstants . MODEL_ATTRIBUTE_NAME_ERROR_DESCRIPTION ) . toString ( ) ; }
Gets error description from .
17,580
protected String getProxyGrantingTicketIou ( final Map < String , Object > model ) { return ( String ) model . get ( CasViewConstants . MODEL_ATTRIBUTE_NAME_PROXY_GRANTING_TICKET_IOU ) ; }
Gets the PGT - IOU from the model .
17,581
protected Map < String , Object > getModelAttributes ( final Map < String , Object > model ) { return ( Map < String , Object > ) model . get ( CasProtocolConstants . VALIDATION_CAS_MODEL_ATTRIBUTE_NAME_ATTRIBUTES ) ; }
Gets model attributes .
17,582
protected Map < String , List < Object > > getPrincipalAttributesAsMultiValuedAttributes ( final Map < String , Object > model ) { return getPrincipal ( model ) . getAttributes ( ) ; }
Gets principal attributes . Single - valued attributes are converted to a collection so the review can easily loop through all .
17,583
protected Service getServiceFrom ( final Map < String , Object > model ) { return ( Service ) model . get ( CasViewConstants . MODEL_ATTRIBUTE_NAME_SERVICE ) ; }
Gets validated service from the model .
17,584
protected Collection < Authentication > getChainedAuthentications ( final Map < String , Object > model ) { val assertion = getAssertionFrom ( model ) ; val chainedAuthentications = assertion . getChainedAuthentications ( ) ; return chainedAuthentications . stream ( ) . limit ( chainedAuthentications . size ( ) - 1 ) . collect ( Collectors . toList ( ) ) ; }
Gets chained authentications . Note that the last index in the list always describes the primary authentication event . All others in the chain should denote proxies . Per the CAS protocol when authentication has proceeded through multiple proxies the order in which the proxies were traversed MUST be reflected in the response . The most recently - visited proxy MUST be the first proxy listed and all the other proxies MUST be shifted down as new proxies are added .
17,585
protected void putIntoModel ( final Map < String , Object > model , final String key , final Object value ) { LOGGER . trace ( "Adding attribute [{}] into the view model for [{}] with value [{}]" , key , getClass ( ) . getSimpleName ( ) , value ) ; model . put ( key , value ) ; }
Put into model .
17,586
protected Map < String , List < Object > > getCasProtocolAuthenticationAttributes ( final Map < String , Object > model , final RegisteredService registeredService ) { val authn = getPrimaryAuthenticationFrom ( model ) ; val assertion = getAssertionFrom ( model ) ; return authenticationAttributeReleasePolicy . getAuthenticationAttributesForRelease ( authn , assertion , model , registeredService ) ; }
Put cas authentication attributes into model .
17,587
protected Map prepareViewModelWithAuthenticationPrincipal ( final Map < String , Object > model ) { putIntoModel ( model , CasViewConstants . MODEL_ATTRIBUTE_NAME_PRINCIPAL , getPrincipal ( model ) ) ; putIntoModel ( model , CasViewConstants . MODEL_ATTRIBUTE_NAME_CHAINED_AUTHENTICATIONS , getChainedAuthentications ( model ) ) ; putIntoModel ( model , CasViewConstants . MODEL_ATTRIBUTE_NAME_PRIMARY_AUTHENTICATION , getPrimaryAuthenticationFrom ( model ) ) ; LOGGER . trace ( "Prepared CAS response output model with attribute names [{}]" , model . keySet ( ) ) ; return model ; }
Prepare view model with authentication principal .
17,588
protected void prepareCasResponseAttributesForViewModel ( final Map < String , Object > model ) { val service = authenticationRequestServiceSelectionStrategies . resolveService ( getServiceFrom ( model ) ) ; val registeredService = this . servicesManager . findServiceBy ( service ) ; val principalAttributes = getCasPrincipalAttributes ( model , registeredService ) ; val attributes = new HashMap < String , Object > ( principalAttributes ) ; LOGGER . trace ( "Processed principal attributes from the output model to be [{}]" , principalAttributes . keySet ( ) ) ; val protocolAttributes = getCasProtocolAuthenticationAttributes ( model , registeredService ) ; attributes . putAll ( protocolAttributes ) ; LOGGER . debug ( "Final collection of attributes for the response are [{}]." , attributes . keySet ( ) ) ; putCasResponseAttributesIntoModel ( model , attributes , registeredService , this . attributesRenderer ) ; }
Prepare cas response attributes for view model .
17,589
protected Map < String , List < Object > > getCasPrincipalAttributes ( final Map < String , Object > model , final RegisteredService registeredService ) { return getPrincipalAttributesAsMultiValuedAttributes ( model ) ; }
Put cas principal attributes into model .
17,590
protected void putCasResponseAttributesIntoModel ( final Map < String , Object > model , final Map < String , Object > attributes , final RegisteredService registeredService , final CasProtocolAttributesRenderer attributesRenderer ) { LOGGER . trace ( "Beginning to encode attributes for the response" ) ; val encodedAttributes = this . protocolAttributeEncoder . encodeAttributes ( attributes , registeredService ) ; LOGGER . debug ( "Encoded attributes for the response are [{}]" , encodedAttributes ) ; putIntoModel ( model , CasProtocolConstants . VALIDATION_CAS_MODEL_ATTRIBUTE_NAME_ATTRIBUTES , encodedAttributes ) ; val formattedAttributes = attributesRenderer . render ( encodedAttributes ) ; putIntoModel ( model , CasProtocolConstants . VALIDATION_CAS_MODEL_ATTRIBUTE_NAME_FORMATTED_ATTRIBUTES , formattedAttributes ) ; }
Put cas response attributes into model .
17,591
@ View ( name = "by_when_action_was_performed" , map = "function(doc) { if(doc.whenActionWasPerformed) { emit(doc.whenActionWasPerformed, doc) } }" ) public List < CouchDbAuditActionContext > findAuditRecordsSince ( final LocalDate localDate ) { return db . queryView ( createQuery ( "by_when_action_was_performed" ) . startKey ( localDate ) . includeDocs ( true ) , CouchDbAuditActionContext . class ) ; }
Find audit records since + localDate + .
17,592
@ View ( name = "by_throttle_params" , map = "classpath:CouchDbAuditActionContext_by_throttle_params.js" ) public List < CouchDbAuditActionContext > findByThrottleParams ( final String remoteAddress , final String username , final String failureCode , final String applicationCode , final LocalDateTime cutoffTime ) { val view = createQuery ( "by_throttle_params" ) . startKey ( ComplexKey . of ( remoteAddress , username , failureCode , applicationCode , cutoffTime ) ) . endKey ( ComplexKey . of ( remoteAddress , username , failureCode , applicationCode , "999999" ) ) ; return db . queryView ( view , CouchDbAuditActionContext . class ) ; }
Find audit records for authentication throttling .
17,593
protected Map < String , Serializable > buildTicketProperties ( final J2EContext webContext ) { val properties = new HashMap < String , Serializable > ( ) ; val themeParamName = casProperties . getTheme ( ) . getParamName ( ) ; val localParamName = casProperties . getLocale ( ) . getParamName ( ) ; properties . put ( themeParamName , StringUtils . defaultString ( webContext . getRequestParameter ( themeParamName ) ) ) ; properties . put ( localParamName , StringUtils . defaultString ( webContext . getRequestParameter ( localParamName ) ) ) ; properties . put ( CasProtocolConstants . PARAMETER_METHOD , StringUtils . defaultString ( webContext . getRequestParameter ( CasProtocolConstants . PARAMETER_METHOD ) ) ) ; return properties ; }
Build the ticket properties .
17,594
protected Service restoreDelegatedAuthenticationRequest ( final RequestContext requestContext , final WebContext webContext , final TransientSessionTicket ticket ) { val service = ticket . getService ( ) ; LOGGER . trace ( "Restoring requested service [{}] back in the authentication flow" , service ) ; WebUtils . putServiceIntoFlowScope ( requestContext , service ) ; webContext . setRequestAttribute ( CasProtocolConstants . PARAMETER_SERVICE , service ) ; val themeParamName = casProperties . getTheme ( ) . getParamName ( ) ; val localParamName = casProperties . getLocale ( ) . getParamName ( ) ; val properties = ticket . getProperties ( ) ; webContext . setRequestAttribute ( themeParamName , properties . get ( themeParamName ) ) ; webContext . setRequestAttribute ( localParamName , properties . get ( localParamName ) ) ; webContext . setRequestAttribute ( CasProtocolConstants . PARAMETER_METHOD , properties . get ( CasProtocolConstants . PARAMETER_METHOD ) ) ; return service ; }
Restore the information saved in the ticket and return the service .
17,595
protected TransientSessionTicket retrieveSessionTicketViaClientId ( final WebContext webContext , final String clientId ) { val ticket = this . ticketRegistry . getTicket ( clientId , TransientSessionTicket . class ) ; if ( ticket == null ) { LOGGER . error ( "Delegated client identifier cannot be located in the authentication request [{}]" , webContext . getFullRequestURL ( ) ) ; throw new UnauthorizedServiceException ( UnauthorizedServiceException . CODE_UNAUTHZ_SERVICE , StringUtils . EMPTY ) ; } if ( ticket . isExpired ( ) ) { LOGGER . error ( "Delegated client identifier [{}] has expired in the authentication request" , ticket . getId ( ) ) ; this . ticketRegistry . deleteTicket ( ticket . getId ( ) ) ; throw new UnauthorizedServiceException ( UnauthorizedServiceException . CODE_UNAUTHZ_SERVICE , StringUtils . EMPTY ) ; } LOGGER . debug ( "Located delegated client identifier as [{}]" , ticket . getId ( ) ) ; return ticket ; }
Retrieve session ticket via client id .
17,596
protected String getDelegatedClientId ( final WebContext webContext , final BaseClient client ) { var clientId = webContext . getRequestParameter ( PARAMETER_CLIENT_ID ) ; if ( StringUtils . isBlank ( clientId ) ) { if ( client instanceof SAML2Client ) { LOGGER . debug ( "Client identifier could not found as part of the request parameters. Looking at relay-state for the SAML2 client" ) ; clientId = webContext . getRequestParameter ( "RelayState" ) ; } if ( client instanceof OAuth20Client || client instanceof OidcClient ) { LOGGER . debug ( "Client identifier could not found as part of the request parameters. Looking at state for the OAuth2/Oidc client" ) ; clientId = webContext . getRequestParameter ( OAuth20Configuration . STATE_REQUEST_PARAMETER ) ; } if ( client instanceof OAuth10Client ) { LOGGER . debug ( "Client identifier could not be found as part of request parameters. Looking at state for the OAuth1 client" ) ; val sessionStore = webContext . getSessionStore ( ) ; clientId = ( String ) sessionStore . get ( webContext , OAUTH10_CLIENT_ID_SESSION_KEY ) ; sessionStore . set ( webContext , OAUTH10_CLIENT_ID_SESSION_KEY , null ) ; } } LOGGER . debug ( "Located delegated client identifier for this request as [{}]" , clientId ) ; return clientId ; }
Gets delegated client id .
17,597
public void setCredentials ( final UsernamePasswordCredential credential ) { val wss4jSecurityInterceptor = new Wss4jSecurityInterceptor ( ) ; wss4jSecurityInterceptor . setSecurementActions ( "Timestamp UsernameToken" ) ; wss4jSecurityInterceptor . setSecurementUsername ( credential . getUsername ( ) ) ; wss4jSecurityInterceptor . setSecurementPassword ( credential . getPassword ( ) ) ; setInterceptors ( new ClientInterceptor [ ] { wss4jSecurityInterceptor } ) ; }
Configure credentials .
17,598
public Map < String , Object > handle ( ) { val model = new HashMap < String , Object > ( ) ; val diff = Duration . between ( this . upTimeStartDate , ZonedDateTime . now ( ZoneOffset . UTC ) ) ; model . put ( "upTime" , diff . getSeconds ( ) ) ; val runtime = Runtime . getRuntime ( ) ; model . put ( "totalMemory" , FileUtils . byteCountToDisplaySize ( runtime . totalMemory ( ) ) ) ; model . put ( "maxMemory" , FileUtils . byteCountToDisplaySize ( runtime . maxMemory ( ) ) ) ; model . put ( "freeMemory" , FileUtils . byteCountToDisplaySize ( runtime . freeMemory ( ) ) ) ; val unexpiredTgts = new AtomicInteger ( ) ; val unexpiredSts = new AtomicInteger ( ) ; val expiredTgts = new AtomicInteger ( ) ; val expiredSts = new AtomicInteger ( ) ; val tickets = this . centralAuthenticationService . getTickets ( ticket -> true ) ; tickets . forEach ( ticket -> { if ( ticket instanceof ServiceTicket ) { if ( ticket . isExpired ( ) ) { this . centralAuthenticationService . deleteTicket ( ticket . getId ( ) ) ; expiredSts . incrementAndGet ( ) ; } else { unexpiredSts . incrementAndGet ( ) ; } } else { if ( ticket . isExpired ( ) ) { this . centralAuthenticationService . deleteTicket ( ticket . getId ( ) ) ; expiredTgts . incrementAndGet ( ) ; } else { unexpiredTgts . incrementAndGet ( ) ; } } } ) ; model . put ( "unexpiredTgts" , unexpiredTgts ) ; model . put ( "unexpiredSts" , unexpiredSts ) ; model . put ( "expiredTgts" , expiredTgts ) ; model . put ( "expiredSts" , expiredSts ) ; return model ; }
Gets availability times of the server .
17,599
private static String [ ] toResources ( final Object [ ] args ) { val object = args [ 0 ] ; if ( object instanceof AuthenticationTransaction ) { val transaction = AuthenticationTransaction . class . cast ( object ) ; return new String [ ] { SUPPLIED_CREDENTIALS + transaction . getCredentials ( ) } ; } return new String [ ] { SUPPLIED_CREDENTIALS + CollectionUtils . wrap ( object ) } ; }
Turn the arguments into a list .