idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
18,400
public static boolean isCasAuthenticationOldForMaxAgeAuthorizationRequest ( final WebContext context , final UserProfile profile ) { val authTime = profile . getAttribute ( CasProtocolConstants . VALIDATION_CAS_MODEL_ATTRIBUTE_NAME_AUTHENTICATION_DATE ) ; if ( authTime == null ) { return false ; } val dt = ZonedDateTime . parse ( authTime . toString ( ) ) ; return isCasAuthenticationOldForMaxAgeAuthorizationRequest ( context , dt ) ; }
Is cas authentication old for max age authorization request?
18,401
@ Scheduled ( initialDelayString = "${cas.authn.throttle.schedule.startDelay:PT10S}" , fixedDelayString = "${cas.authn.throttle.schedule.repeatInterval:PT15S}" ) public void run ( ) { val handlers = authenticationThrottlingExecutionPlan . getAuthenticationThrottleInterceptors ( ) ; handlers . stream ( ) . filter ( handler -> handler instanceof ThrottledSubmissionHandlerInterceptor ) . map ( handler -> ( ThrottledSubmissionHandlerInterceptor ) handler ) . forEach ( ThrottledSubmissionHandlerInterceptor :: decrement ) ; }
Kicks off the job that attempts to clean the throttling submission record history .
18,402
protected void createLoginFormView ( final Flow flow ) { val propertiesToBind = CollectionUtils . wrapList ( "username" , "password" , "source" ) ; val binder = createStateBinderConfiguration ( propertiesToBind ) ; casProperties . getView ( ) . getCustomLoginFormFields ( ) . forEach ( ( field , props ) -> { val fieldName = String . format ( "customFields[%s]" , field ) ; binder . addBinding ( new BinderConfiguration . Binding ( fieldName , props . getConverter ( ) , props . isRequired ( ) ) ) ; } ) ; val state = createViewState ( flow , CasWebflowConstants . STATE_ID_VIEW_LOGIN_FORM , "casLoginView" , binder ) ; state . getRenderActionList ( ) . add ( createEvaluateAction ( CasWebflowConstants . ACTION_ID_RENDER_LOGIN_FORM ) ) ; createStateModelBinding ( state , CasWebflowConstants . VAR_ID_CREDENTIAL , UsernamePasswordCredential . class ) ; val transition = createTransitionForState ( state , CasWebflowConstants . TRANSITION_ID_SUBMIT , CasWebflowConstants . STATE_ID_REAL_SUBMIT ) ; val attributes = transition . getAttributes ( ) ; attributes . put ( "bind" , Boolean . TRUE ) ; attributes . put ( "validate" , Boolean . TRUE ) ; attributes . put ( "history" , History . INVALIDATE ) ; }
Create login form view .
18,403
protected void createAuthenticationWarningMessagesView ( final Flow flow ) { val state = createViewState ( flow , CasWebflowConstants . STATE_ID_SHOW_AUTHN_WARNING_MSGS , "casLoginMessageView" ) ; val setAction = createSetAction ( "requestScope.messages" , "messageContext.allMessages" ) ; state . getEntryActionList ( ) . add ( setAction ) ; createTransitionForState ( state , CasWebflowConstants . TRANSITION_ID_PROCEED , CasWebflowConstants . STATE_ID_PROCEED_FROM_AUTHENTICATION_WARNINGS_VIEW ) ; val proceedAction = createActionState ( flow , CasWebflowConstants . STATE_ID_PROCEED_FROM_AUTHENTICATION_WARNINGS_VIEW ) ; proceedAction . getActionList ( ) . add ( createEvaluateAction ( CasWebflowConstants . ACTION_ID_SEND_TICKET_GRANTING_TICKET ) ) ; createStateDefaultTransition ( proceedAction , CasWebflowConstants . STATE_ID_SERVICE_CHECK ) ; }
Create authentication warning messages view .
18,404
protected void createRememberMeAuthnWebflowConfig ( final Flow flow ) { if ( casProperties . getTicket ( ) . getTgt ( ) . getRememberMe ( ) . isEnabled ( ) ) { createFlowVariable ( flow , CasWebflowConstants . VAR_ID_CREDENTIAL , RememberMeUsernamePasswordCredential . class ) ; val state = getState ( flow , CasWebflowConstants . STATE_ID_VIEW_LOGIN_FORM , ViewState . class ) ; val cfg = getViewStateBinderConfiguration ( state ) ; cfg . addBinding ( new BinderConfiguration . Binding ( "rememberMe" , null , false ) ) ; } else { createFlowVariable ( flow , CasWebflowConstants . VAR_ID_CREDENTIAL , UsernamePasswordCredential . class ) ; } }
Create remember me authn webflow config .
18,405
protected void createDefaultActionStates ( final Flow flow ) { createRealSubmitAction ( flow ) ; createInitialAuthenticationRequestValidationCheckAction ( flow ) ; createCreateTicketGrantingTicketAction ( flow ) ; createSendTicketGrantingTicketAction ( flow ) ; createGenerateServiceTicketAction ( flow ) ; createGatewayServicesMgmtAction ( flow ) ; createServiceAuthorizationCheckAction ( flow ) ; createRedirectToServiceActionState ( flow ) ; createHandleAuthenticationFailureAction ( flow ) ; createTerminateSessionAction ( flow ) ; createTicketGrantingTicketCheckAction ( flow ) ; }
Create default action states .
18,406
protected void createRealSubmitAction ( final Flow flow ) { val state = createActionState ( flow , CasWebflowConstants . STATE_ID_REAL_SUBMIT , "authenticationViaFormAction" ) ; createTransitionForState ( state , CasWebflowConstants . TRANSITION_ID_WARN , CasWebflowConstants . STATE_ID_WARN ) ; createTransitionForState ( state , CasWebflowConstants . TRANSITION_ID_SUCCESS , CasWebflowConstants . STATE_ID_CREATE_TICKET_GRANTING_TICKET ) ; createTransitionForState ( state , CasWebflowConstants . TRANSITION_ID_SUCCESS_WITH_WARNINGS , CasWebflowConstants . STATE_ID_SHOW_AUTHN_WARNING_MSGS ) ; createTransitionForState ( state , CasWebflowConstants . TRANSITION_ID_AUTHENTICATION_FAILURE , CasWebflowConstants . STATE_ID_HANDLE_AUTHN_FAILURE ) ; createTransitionForState ( state , CasWebflowConstants . TRANSITION_ID_ERROR , CasWebflowConstants . STATE_ID_INIT_LOGIN_FORM ) ; }
Create real submit action .
18,407
protected void createTicketGrantingTicketCheckAction ( final Flow flow ) { val action = createActionState ( flow , CasWebflowConstants . STATE_ID_TICKET_GRANTING_TICKET_CHECK , CasWebflowConstants . ACTION_ID_TICKET_GRANTING_TICKET_CHECK ) ; createTransitionForState ( action , CasWebflowConstants . TRANSITION_ID_TGT_NOT_EXISTS , CasWebflowConstants . STATE_ID_GATEWAY_REQUEST_CHECK ) ; createTransitionForState ( action , CasWebflowConstants . TRANSITION_ID_TGT_INVALID , CasWebflowConstants . STATE_ID_TERMINATE_SESSION ) ; createTransitionForState ( action , CasWebflowConstants . TRANSITION_ID_TGT_VALID , CasWebflowConstants . STATE_ID_HAS_SERVICE_CHECK ) ; }
Create ticket granting ticket check action .
18,408
protected void createInitialAuthenticationRequestValidationCheckAction ( final Flow flow ) { val action = createActionState ( flow , CasWebflowConstants . STATE_ID_INITIAL_AUTHN_REQUEST_VALIDATION_CHECK , CasWebflowConstants . ACTION_ID_INITIAL_AUTHN_REQUEST_VALIDATION ) ; createTransitionForState ( action , CasWebflowConstants . TRANSITION_ID_AUTHENTICATION_FAILURE , CasWebflowConstants . STATE_ID_HANDLE_AUTHN_FAILURE ) ; createTransitionForState ( action , CasWebflowConstants . TRANSITION_ID_ERROR , CasWebflowConstants . STATE_ID_INIT_LOGIN_FORM ) ; createTransitionForState ( action , CasWebflowConstants . TRANSITION_ID_SUCCESS , CasWebflowConstants . STATE_ID_TICKET_GRANTING_TICKET_CHECK ) ; createTransitionForState ( action , CasWebflowConstants . TRANSITION_ID_SUCCESS_WITH_WARNINGS , CasWebflowConstants . STATE_ID_SHOW_AUTHN_WARNING_MSGS ) ; }
Create initial authentication request validation check action .
18,409
protected void createTerminateSessionAction ( final Flow flow ) { val terminateSession = createActionState ( flow , CasWebflowConstants . STATE_ID_TERMINATE_SESSION , createEvaluateAction ( CasWebflowConstants . ACTION_ID_TERMINATE_SESSION ) ) ; createStateDefaultTransition ( terminateSession , CasWebflowConstants . STATE_ID_GATEWAY_REQUEST_CHECK ) ; }
Create terminate session action .
18,410
protected void createSendTicketGrantingTicketAction ( final Flow flow ) { val action = createActionState ( flow , CasWebflowConstants . STATE_ID_SEND_TICKET_GRANTING_TICKET , CasWebflowConstants . ACTION_ID_SEND_TICKET_GRANTING_TICKET ) ; createTransitionForState ( action , CasWebflowConstants . TRANSITION_ID_SUCCESS , CasWebflowConstants . STATE_ID_SERVICE_CHECK ) ; createTransitionForState ( action , CasWebflowConstants . TRANSITION_ID_SUCCESS_WITH_WARNINGS , CasWebflowConstants . STATE_ID_SHOW_AUTHN_WARNING_MSGS ) ; }
Create send ticket granting ticket action .
18,411
protected void createCreateTicketGrantingTicketAction ( final Flow flow ) { val action = createActionState ( flow , CasWebflowConstants . STATE_ID_CREATE_TICKET_GRANTING_TICKET , CasWebflowConstants . ACTION_ID_CREATE_TICKET_GRANTING_TICKET ) ; createTransitionForState ( action , CasWebflowConstants . TRANSITION_ID_SUCCESS_WITH_WARNINGS , CasWebflowConstants . STATE_ID_SHOW_AUTHN_WARNING_MSGS ) ; createTransitionForState ( action , CasWebflowConstants . TRANSITION_ID_SUCCESS , CasWebflowConstants . STATE_ID_SEND_TICKET_GRANTING_TICKET ) ; }
Create create ticket granting ticket action .
18,412
protected void createGenerateServiceTicketAction ( final Flow flow ) { val handler = createActionState ( flow , CasWebflowConstants . STATE_ID_GENERATE_SERVICE_TICKET , createEvaluateAction ( CasWebflowConstants . ACTION_ID_GENERATE_SERVICE_TICKET ) ) ; createTransitionForState ( handler , CasWebflowConstants . TRANSITION_ID_SUCCESS , CasWebflowConstants . STATE_ID_REDIRECT ) ; createTransitionForState ( handler , CasWebflowConstants . TRANSITION_ID_WARN , CasWebflowConstants . STATE_ID_WARN ) ; createTransitionForState ( handler , CasWebflowConstants . TRANSITION_ID_AUTHENTICATION_FAILURE , CasWebflowConstants . STATE_ID_HANDLE_AUTHN_FAILURE ) ; createTransitionForState ( handler , CasWebflowConstants . TRANSITION_ID_ERROR , CasWebflowConstants . STATE_ID_INIT_LOGIN_FORM ) ; createTransitionForState ( handler , CasWebflowConstants . TRANSITION_ID_GATEWAY , CasWebflowConstants . STATE_ID_GATEWAY_SERVICES_MGMT_CHECK ) ; }
Create generate service ticket action .
18,413
protected void createHandleAuthenticationFailureAction ( final Flow flow ) { val handler = createActionState ( flow , CasWebflowConstants . STATE_ID_HANDLE_AUTHN_FAILURE , CasWebflowConstants . ACTION_ID_AUTHENTICATION_EXCEPTION_HANDLER ) ; createTransitionForState ( handler , AccountDisabledException . class . getSimpleName ( ) , CasWebflowConstants . VIEW_ID_ACCOUNT_DISABLED ) ; createTransitionForState ( handler , AccountLockedException . class . getSimpleName ( ) , CasWebflowConstants . VIEW_ID_ACCOUNT_LOCKED ) ; createTransitionForState ( handler , AccountPasswordMustChangeException . class . getSimpleName ( ) , CasWebflowConstants . VIEW_ID_MUST_CHANGE_PASSWORD ) ; createTransitionForState ( handler , CredentialExpiredException . class . getSimpleName ( ) , CasWebflowConstants . VIEW_ID_EXPIRED_PASSWORD ) ; createTransitionForState ( handler , InvalidLoginLocationException . class . getSimpleName ( ) , CasWebflowConstants . VIEW_ID_INVALID_WORKSTATION ) ; createTransitionForState ( handler , InvalidLoginTimeException . class . getSimpleName ( ) , CasWebflowConstants . VIEW_ID_INVALID_AUTHENTICATION_HOURS ) ; createTransitionForState ( handler , FailedLoginException . class . getSimpleName ( ) , CasWebflowConstants . STATE_ID_INIT_LOGIN_FORM ) ; createTransitionForState ( handler , AccountNotFoundException . class . getSimpleName ( ) , CasWebflowConstants . STATE_ID_INIT_LOGIN_FORM ) ; createTransitionForState ( handler , UnauthorizedServiceForPrincipalException . class . getSimpleName ( ) , CasWebflowConstants . STATE_ID_INIT_LOGIN_FORM ) ; createTransitionForState ( handler , PrincipalException . class . getSimpleName ( ) , CasWebflowConstants . STATE_ID_INIT_LOGIN_FORM ) ; createTransitionForState ( handler , UnsatisfiedAuthenticationPolicyException . class . getSimpleName ( ) , CasWebflowConstants . STATE_ID_INIT_LOGIN_FORM ) ; createTransitionForState ( handler , UnauthorizedAuthenticationException . class . getSimpleName ( ) , CasWebflowConstants . VIEW_ID_AUTHENTICATION_BLOCKED ) ; createTransitionForState ( handler , CasWebflowConstants . STATE_ID_SERVICE_UNAUTHZ_CHECK , CasWebflowConstants . STATE_ID_SERVICE_UNAUTHZ_CHECK ) ; createStateDefaultTransition ( handler , CasWebflowConstants . STATE_ID_INIT_LOGIN_FORM ) ; }
Create handle authentication failure action .
18,414
protected void createRedirectToServiceActionState ( final Flow flow ) { val redirectToView = createActionState ( flow , CasWebflowConstants . STATE_ID_REDIRECT , CasWebflowConstants . ACTION_ID_REDIRECT_TO_SERVICE ) ; createTransitionForState ( redirectToView , Response . ResponseType . POST . name ( ) . toLowerCase ( ) , CasWebflowConstants . STATE_ID_POST_VIEW ) ; createTransitionForState ( redirectToView , Response . ResponseType . HEADER . name ( ) . toLowerCase ( ) , CasWebflowConstants . STATE_ID_HEADER_VIEW ) ; createTransitionForState ( redirectToView , Response . ResponseType . REDIRECT . name ( ) . toLowerCase ( ) , CasWebflowConstants . STATE_ID_REDIRECT_VIEW ) ; }
Create redirect to service action state .
18,415
protected void createServiceAuthorizationCheckAction ( final Flow flow ) { val serviceAuthorizationCheck = createActionState ( flow , CasWebflowConstants . STATE_ID_SERVICE_AUTHZ_CHECK , "serviceAuthorizationCheck" ) ; createStateDefaultTransition ( serviceAuthorizationCheck , CasWebflowConstants . STATE_ID_INIT_LOGIN_FORM ) ; }
Create service authorization check action .
18,416
protected void createGatewayServicesMgmtAction ( final Flow flow ) { val gatewayServicesManagementCheck = createActionState ( flow , CasWebflowConstants . STATE_ID_GATEWAY_SERVICES_MGMT_CHECK , "gatewayServicesManagementCheck" ) ; createTransitionForState ( gatewayServicesManagementCheck , CasWebflowConstants . STATE_ID_SUCCESS , CasWebflowConstants . STATE_ID_REDIRECT ) ; }
Create gateway services mgmt action .
18,417
protected void createInjectHeadersActionState ( final Flow flow ) { val headerState = createActionState ( flow , CasWebflowConstants . STATE_ID_HEADER_VIEW , "injectResponseHeadersAction" ) ; createTransitionForState ( headerState , CasWebflowConstants . TRANSITION_ID_SUCCESS , CasWebflowConstants . STATE_ID_END_WEBFLOW ) ; createTransitionForState ( headerState , CasWebflowConstants . TRANSITION_ID_REDIRECT , CasWebflowConstants . STATE_ID_REDIRECT_VIEW ) ; }
Create header end state .
18,418
protected void createRedirectUnauthorizedServiceUrlEndState ( final Flow flow ) { val state = createEndState ( flow , CasWebflowConstants . STATE_ID_VIEW_REDIR_UNAUTHZ_URL , "flowScope.unauthorizedRedirectUrl" , true ) ; state . getEntryActionList ( ) . add ( createEvaluateAction ( "redirectUnauthorizedServiceUrlAction" ) ) ; }
Create redirect unauthorized service url end state .
18,419
protected void createGenericLoginSuccessEndState ( final Flow flow ) { val state = createEndState ( flow , CasWebflowConstants . STATE_ID_VIEW_GENERIC_LOGIN_SUCCESS , CasWebflowConstants . VIEW_ID_GENERIC_SUCCESS ) ; state . getEntryActionList ( ) . add ( createEvaluateAction ( "genericSuccessViewAction" ) ) ; }
Create generic login success end state .
18,420
protected void createServiceWarningViewState ( final Flow flow ) { val stateWarning = createViewState ( flow , CasWebflowConstants . STATE_ID_SHOW_WARNING_VIEW , CasWebflowConstants . VIEW_ID_CONFIRM ) ; createTransitionForState ( stateWarning , CasWebflowConstants . TRANSITION_ID_SUCCESS , "finalizeWarning" ) ; val finalizeWarn = createActionState ( flow , "finalizeWarning" , createEvaluateAction ( "serviceWarningAction" ) ) ; createTransitionForState ( finalizeWarn , CasWebflowConstants . STATE_ID_REDIRECT , CasWebflowConstants . STATE_ID_REDIRECT ) ; }
Create service warning view state .
18,421
protected void createDefaultDecisionStates ( final Flow flow ) { createServiceUnauthorizedCheckDecisionState ( flow ) ; createServiceCheckDecisionState ( flow ) ; createWarnDecisionState ( flow ) ; createGatewayRequestCheckDecisionState ( flow ) ; createHasServiceCheckDecisionState ( flow ) ; createRenewCheckActionState ( flow ) ; }
Create default decision states .
18,422
protected void createServiceUnauthorizedCheckDecisionState ( final Flow flow ) { val decision = createDecisionState ( flow , CasWebflowConstants . STATE_ID_SERVICE_UNAUTHZ_CHECK , "flowScope.unauthorizedRedirectUrl != null" , CasWebflowConstants . STATE_ID_VIEW_REDIR_UNAUTHZ_URL , CasWebflowConstants . STATE_ID_VIEW_SERVICE_ERROR ) ; decision . getEntryActionList ( ) . add ( createEvaluateAction ( "setServiceUnauthorizedRedirectUrlAction" ) ) ; }
Create service unauthorized check decision state .
18,423
protected void createServiceCheckDecisionState ( final Flow flow ) { createDecisionState ( flow , CasWebflowConstants . STATE_ID_SERVICE_CHECK , "flowScope.service != null" , CasWebflowConstants . STATE_ID_GENERATE_SERVICE_TICKET , CasWebflowConstants . STATE_ID_VIEW_GENERIC_LOGIN_SUCCESS ) ; }
Create service check decision state .
18,424
protected void createWarnDecisionState ( final Flow flow ) { createDecisionState ( flow , CasWebflowConstants . STATE_ID_WARN , "flowScope.warnCookieValue" , CasWebflowConstants . STATE_ID_SHOW_WARNING_VIEW , CasWebflowConstants . STATE_ID_REDIRECT ) ; }
Create warn decision state .
18,425
protected void createGatewayRequestCheckDecisionState ( final Flow flow ) { createDecisionState ( flow , CasWebflowConstants . STATE_ID_GATEWAY_REQUEST_CHECK , "requestParameters.gateway != '' and requestParameters.gateway != null and flowScope.service != null" , CasWebflowConstants . STATE_ID_GATEWAY_SERVICES_MGMT_CHECK , CasWebflowConstants . STATE_ID_SERVICE_AUTHZ_CHECK ) ; }
Create gateway request check decision state .
18,426
protected void createHasServiceCheckDecisionState ( final Flow flow ) { createDecisionState ( flow , CasWebflowConstants . STATE_ID_HAS_SERVICE_CHECK , "flowScope.service != null" , CasWebflowConstants . STATE_ID_RENEW_REQUEST_CHECK , CasWebflowConstants . STATE_ID_VIEW_GENERIC_LOGIN_SUCCESS ) ; }
Create has service check decision state .
18,427
protected void createRenewCheckActionState ( final Flow flow ) { val action = createActionState ( flow , CasWebflowConstants . STATE_ID_RENEW_REQUEST_CHECK , CasWebflowConstants . ACTION_ID_RENEW_AUTHN_REQUEST ) ; createTransitionForState ( action , CasWebflowConstants . TRANSITION_ID_PROCEED , CasWebflowConstants . STATE_ID_GENERATE_SERVICE_TICKET ) ; createTransitionForState ( action , CasWebflowConstants . TRANSITION_ID_RENEW , CasWebflowConstants . STATE_ID_SERVICE_AUTHZ_CHECK ) ; createStateDefaultTransition ( action , CasWebflowConstants . STATE_ID_SERVICE_AUTHZ_CHECK ) ; }
Create renew check state .
18,428
public String getNewTicketId ( final String prefix ) { val number = this . numericGenerator . getNextNumberAsString ( ) ; val ticketBody = this . randomStringGenerator . getNewString ( ) . replace ( '_' , '-' ) ; val origSuffix = StringUtils . defaultString ( this . suffix ) ; val finalizedSuffix = StringUtils . isEmpty ( origSuffix ) ? origSuffix : '-' + origSuffix ; return prefix + '-' + number + '-' + ticketBody + finalizedSuffix ; }
Due to a bug in mod - auth - cas and possibly other clients in the way tickets are parsed the ticket id body is sanitized to remove the character _ replacing it with - instead . This might be revisited in the future and removed once at least mod - auth - cas fixes the issue .
18,429
public boolean isUndefined ( ) { return StringUtils . isBlank ( text ) || StringUtils . isBlank ( from ) || StringUtils . isBlank ( subject ) ; }
Indicate whether email settings are defined .
18,430
public String getFormattedBody ( final Object ... arguments ) { if ( StringUtils . isBlank ( this . text ) ) { LOGGER . warn ( "No email body is defined" ) ; return StringUtils . EMPTY ; } try { val templateFile = ResourceUtils . getFile ( this . text ) ; val contents = FileUtils . readFileToString ( templateFile , StandardCharsets . UTF_8 ) ; return String . format ( contents , arguments ) ; } catch ( final Exception e ) { LOGGER . trace ( e . getMessage ( ) , e ) ; return String . format ( this . text , arguments ) ; } }
Format body .
18,431
private Collection < Map < String , Object > > getActiveSsoSessions ( final SsoSessionReportOptions option ) { val activeSessions = new ArrayList < Map < String , Object > > ( ) ; val dateFormat = new ISOStandardDateFormat ( ) ; getNonExpiredTicketGrantingTickets ( ) . stream ( ) . map ( TicketGrantingTicket . class :: cast ) . filter ( tgt -> ! ( option == SsoSessionReportOptions . DIRECT && tgt . getProxiedBy ( ) != null ) ) . forEach ( tgt -> { val authentication = tgt . getAuthentication ( ) ; val principal = authentication . getPrincipal ( ) ; val sso = new HashMap < String , Object > ( SsoSessionAttributeKeys . values ( ) . length ) ; sso . put ( SsoSessionAttributeKeys . AUTHENTICATED_PRINCIPAL . toString ( ) , principal . getId ( ) ) ; sso . put ( SsoSessionAttributeKeys . AUTHENTICATION_DATE . toString ( ) , authentication . getAuthenticationDate ( ) ) ; sso . put ( SsoSessionAttributeKeys . AUTHENTICATION_DATE_FORMATTED . toString ( ) , dateFormat . format ( DateTimeUtils . dateOf ( authentication . getAuthenticationDate ( ) ) ) ) ; sso . put ( SsoSessionAttributeKeys . NUMBER_OF_USES . toString ( ) , tgt . getCountOfUses ( ) ) ; sso . put ( SsoSessionAttributeKeys . TICKET_GRANTING_TICKET . toString ( ) , tgt . getId ( ) ) ; sso . put ( SsoSessionAttributeKeys . PRINCIPAL_ATTRIBUTES . toString ( ) , principal . getAttributes ( ) ) ; sso . put ( SsoSessionAttributeKeys . AUTHENTICATION_ATTRIBUTES . toString ( ) , authentication . getAttributes ( ) ) ; if ( option != SsoSessionReportOptions . DIRECT ) { if ( tgt . getProxiedBy ( ) != null ) { sso . put ( SsoSessionAttributeKeys . IS_PROXIED . toString ( ) , Boolean . TRUE ) ; sso . put ( SsoSessionAttributeKeys . PROXIED_BY . toString ( ) , tgt . getProxiedBy ( ) . getId ( ) ) ; } else { sso . put ( SsoSessionAttributeKeys . IS_PROXIED . toString ( ) , Boolean . FALSE ) ; } } sso . put ( SsoSessionAttributeKeys . AUTHENTICATED_SERVICES . toString ( ) , tgt . getServices ( ) ) ; activeSessions . add ( sso ) ; } ) ; return activeSessions ; }
Gets sso sessions .
18,432
private Collection < Ticket > getNonExpiredTicketGrantingTickets ( ) { return this . centralAuthenticationService . getTickets ( ticket -> ticket instanceof TicketGrantingTicket && ! ticket . isExpired ( ) ) ; }
Gets non expired ticket granting tickets .
18,433
public Map < String , Object > getSsoSessions ( final String type ) { val sessionsMap = new HashMap < String , Object > ( 1 ) ; val option = SsoSessionReportOptions . valueOf ( type ) ; val activeSsoSessions = getActiveSsoSessions ( option ) ; sessionsMap . put ( "activeSsoSessions" , activeSsoSessions ) ; val totalTicketGrantingTickets = new AtomicLong ( ) ; val totalProxyGrantingTickets = new AtomicLong ( ) ; val totalUsageCount = new AtomicLong ( ) ; val uniquePrincipals = new HashSet < Object > ( ) ; for ( val activeSsoSession : activeSsoSessions ) { if ( activeSsoSession . containsKey ( SsoSessionAttributeKeys . IS_PROXIED . toString ( ) ) ) { val isProxied = Boolean . valueOf ( activeSsoSession . get ( SsoSessionAttributeKeys . IS_PROXIED . toString ( ) ) . toString ( ) ) ; if ( isProxied ) { totalProxyGrantingTickets . incrementAndGet ( ) ; } else { totalTicketGrantingTickets . incrementAndGet ( ) ; val principal = activeSsoSession . get ( SsoSessionAttributeKeys . AUTHENTICATED_PRINCIPAL . toString ( ) ) . toString ( ) ; uniquePrincipals . add ( principal ) ; } } else { totalTicketGrantingTickets . incrementAndGet ( ) ; val principal = activeSsoSession . get ( SsoSessionAttributeKeys . AUTHENTICATED_PRINCIPAL . toString ( ) ) . toString ( ) ; uniquePrincipals . add ( principal ) ; } val uses = Long . parseLong ( activeSsoSession . get ( SsoSessionAttributeKeys . NUMBER_OF_USES . toString ( ) ) . toString ( ) ) ; totalUsageCount . getAndAdd ( uses ) ; } sessionsMap . put ( "totalProxyGrantingTickets" , totalProxyGrantingTickets ) ; sessionsMap . put ( "totalTicketGrantingTickets" , totalTicketGrantingTickets ) ; sessionsMap . put ( "totalTickets" , totalTicketGrantingTickets . longValue ( ) + totalProxyGrantingTickets . longValue ( ) ) ; sessionsMap . put ( "totalPrincipals" , uniquePrincipals . size ( ) ) ; sessionsMap . put ( "totalUsageCount" , totalUsageCount ) ; return sessionsMap ; }
Endpoint for getting SSO Sessions in JSON format .
18,434
public Map < String , Object > destroySsoSession ( final String ticketGrantingTicket ) { val sessionsMap = new HashMap < String , Object > ( 1 ) ; try { this . centralAuthenticationService . destroyTicketGrantingTicket ( ticketGrantingTicket ) ; sessionsMap . put ( STATUS , HttpServletResponse . SC_OK ) ; sessionsMap . put ( TICKET_GRANTING_TICKET , ticketGrantingTicket ) ; } catch ( final Exception e ) { LOGGER . error ( e . getMessage ( ) , e ) ; sessionsMap . put ( STATUS , HttpServletResponse . SC_INTERNAL_SERVER_ERROR ) ; sessionsMap . put ( TICKET_GRANTING_TICKET , ticketGrantingTicket ) ; sessionsMap . put ( "message" , e . getMessage ( ) ) ; } return sessionsMap ; }
Endpoint for destroying a single SSO Session .
18,435
public Map < String , Object > destroySsoSessions ( final String type ) { val sessionsMap = new HashMap < String , Object > ( ) ; val failedTickets = new HashMap < String , String > ( ) ; val option = SsoSessionReportOptions . valueOf ( type ) ; val collection = getActiveSsoSessions ( option ) ; collection . stream ( ) . map ( sso -> sso . get ( SsoSessionAttributeKeys . TICKET_GRANTING_TICKET . toString ( ) ) . toString ( ) ) . forEach ( ticketGrantingTicket -> { try { this . centralAuthenticationService . destroyTicketGrantingTicket ( ticketGrantingTicket ) ; } catch ( final Exception e ) { LOGGER . error ( e . getMessage ( ) , e ) ; failedTickets . put ( ticketGrantingTicket , e . getMessage ( ) ) ; } } ) ; if ( failedTickets . isEmpty ( ) ) { sessionsMap . put ( STATUS , HttpServletResponse . SC_OK ) ; } else { sessionsMap . put ( STATUS , HttpServletResponse . SC_INTERNAL_SERVER_ERROR ) ; sessionsMap . put ( "failedTicketGrantingTickets" , failedTickets ) ; } return sessionsMap ; }
Destroy sso sessions map .
18,436
public boolean isValid ( ) { return StringUtils . isNotBlank ( this . latitude ) && StringUtils . isNotBlank ( this . longitude ) && StringUtils . isNotBlank ( this . accuracy ) && StringUtils . isNotBlank ( this . timestamp ) ; }
Check whether the geolocation contains enough data to proceed .
18,437
@ ReadOperation ( produces = { ActuatorMediaType . V2_JSON , "application/vnd.cas.services+yaml" , MediaType . APPLICATION_JSON_VALUE } ) public Collection < RegisteredService > handle ( ) { return this . servicesManager . load ( ) ; }
Handle and produce a list of services from registry .
18,438
@ ReadOperation ( produces = { ActuatorMediaType . V2_JSON , "application/vnd.cas.services+yaml" , MediaType . APPLICATION_JSON_VALUE } ) public RegisteredService fetchService ( final String id ) { if ( NumberUtils . isDigits ( id ) ) { return this . servicesManager . findServiceBy ( Long . parseLong ( id ) ) ; } return this . servicesManager . findServiceBy ( id ) ; }
Fetch service either by numeric id or service id pattern .
18,439
@ DeleteOperation ( produces = { ActuatorMediaType . V2_JSON , "application/vnd.cas.services+yaml" , MediaType . APPLICATION_JSON_VALUE } ) public RegisteredService deleteService ( final String id ) { if ( NumberUtils . isDigits ( id ) ) { val svc = this . servicesManager . findServiceBy ( Long . parseLong ( id ) ) ; if ( svc != null ) { return this . servicesManager . delete ( svc ) ; } } else { val svc = this . servicesManager . findServiceBy ( id ) ; if ( svc != null ) { return this . servicesManager . delete ( svc ) ; } } LOGGER . warn ( "Could not locate service definition by id [{}]" , id ) ; return null ; }
Delete registered service .
18,440
protected SamlRegisteredService verifySamlRegisteredService ( final String serviceId ) { if ( StringUtils . isBlank ( serviceId ) ) { throw new UnauthorizedServiceException ( UnauthorizedServiceException . CODE_UNAUTHZ_SERVICE , "Could not verify/locate SAML registered service since no serviceId is provided" ) ; } LOGGER . debug ( "Checking service access in CAS service registry for [{}]" , serviceId ) ; val registeredService = samlProfileHandlerConfigurationContext . getServicesManager ( ) . findServiceBy ( samlProfileHandlerConfigurationContext . getWebApplicationServiceFactory ( ) . createService ( serviceId ) ) ; if ( registeredService == null || ! registeredService . getAccessStrategy ( ) . isServiceAccessAllowed ( ) ) { LOGGER . warn ( "[{}] is not found in the registry or service access is denied. Ensure service is registered in service registry" , serviceId ) ; throw new UnauthorizedServiceException ( UnauthorizedServiceException . CODE_UNAUTHZ_SERVICE ) ; } if ( registeredService instanceof SamlRegisteredService ) { val samlRegisteredService = ( SamlRegisteredService ) registeredService ; LOGGER . debug ( "Located SAML service in the registry as [{}] with the metadata location of [{}]" , samlRegisteredService . getServiceId ( ) , samlRegisteredService . getMetadataLocation ( ) ) ; return samlRegisteredService ; } LOGGER . error ( "CAS has found a match for service [{}] in registry but the match is not defined as a SAML service" , serviceId ) ; throw new UnauthorizedServiceException ( UnauthorizedServiceException . CODE_UNAUTHZ_SERVICE ) ; }
Gets registered service and verify .
18,441
protected AuthnRequest retrieveSamlAuthenticationRequestFromHttpRequest ( final HttpServletRequest request ) throws Exception { LOGGER . debug ( "Retrieving authentication request from scope" ) ; val requestValue = request . getParameter ( SamlProtocolConstants . PARAMETER_SAML_REQUEST ) ; if ( StringUtils . isBlank ( requestValue ) ) { throw new IllegalArgumentException ( "SAML request could not be determined from the authentication request" ) ; } val encodedRequest = EncodingUtils . decodeBase64 ( requestValue . getBytes ( StandardCharsets . UTF_8 ) ) ; return ( AuthnRequest ) XMLObjectSupport . unmarshallFromInputStream ( samlProfileHandlerConfigurationContext . getOpenSamlConfigBean ( ) . getParserPool ( ) , new ByteArrayInputStream ( encodedRequest ) ) ; }
Retrieve authn request authn request .
18,442
protected void logCasValidationAssertion ( final Assertion assertion ) { LOGGER . debug ( "CAS Assertion Valid: [{}]" , assertion . isValid ( ) ) ; LOGGER . debug ( "CAS Assertion Principal: [{}]" , assertion . getPrincipal ( ) . getName ( ) ) ; LOGGER . debug ( "CAS Assertion authentication Date: [{}]" , assertion . getAuthenticationDate ( ) ) ; LOGGER . debug ( "CAS Assertion ValidFrom Date: [{}]" , assertion . getValidFromDate ( ) ) ; LOGGER . debug ( "CAS Assertion ValidUntil Date: [{}]" , assertion . getValidUntilDate ( ) ) ; LOGGER . debug ( "CAS Assertion Attributes: [{}]" , assertion . getAttributes ( ) ) ; LOGGER . debug ( "CAS Assertion Principal Attributes: [{}]" , assertion . getPrincipal ( ) . getAttributes ( ) ) ; }
Log cas validation assertion .
18,443
protected void issueAuthenticationRequestRedirect ( final Pair < ? extends SignableSAMLObject , MessageContext > pair , final HttpServletRequest request , final HttpServletResponse response ) throws Exception { val authnRequest = ( AuthnRequest ) pair . getLeft ( ) ; val serviceUrl = constructServiceUrl ( request , response , pair ) ; LOGGER . debug ( "Created service url [{}]" , DigestUtils . abbreviate ( serviceUrl ) ) ; val initialUrl = CommonUtils . constructRedirectUrl ( samlProfileHandlerConfigurationContext . getCasProperties ( ) . getServer ( ) . getLoginUrl ( ) , CasProtocolConstants . PARAMETER_SERVICE , serviceUrl , authnRequest . isForceAuthn ( ) , authnRequest . isPassive ( ) ) ; val urlToRedirectTo = buildRedirectUrlByRequestedAuthnContext ( initialUrl , authnRequest , request ) ; LOGGER . debug ( "Redirecting SAML authN request to [{}]" , urlToRedirectTo ) ; val authenticationRedirectStrategy = new DefaultAuthenticationRedirectStrategy ( ) ; authenticationRedirectStrategy . redirect ( request , response , urlToRedirectTo ) ; }
Redirect request for authentication .
18,444
protected Map < String , String > getAuthenticationContextMappings ( ) { val authnContexts = samlProfileHandlerConfigurationContext . getCasProperties ( ) . getAuthn ( ) . getSamlIdp ( ) . getAuthenticationContextClassMappings ( ) ; return CollectionUtils . convertDirectedListToMap ( authnContexts ) ; }
Gets authentication context mappings .
18,445
protected String buildRedirectUrlByRequestedAuthnContext ( final String initialUrl , final AuthnRequest authnRequest , final HttpServletRequest request ) { val authenticationContextClassMappings = samlProfileHandlerConfigurationContext . getCasProperties ( ) . getAuthn ( ) . getSamlIdp ( ) . getAuthenticationContextClassMappings ( ) ; if ( authnRequest . getRequestedAuthnContext ( ) == null || authenticationContextClassMappings == null || authenticationContextClassMappings . isEmpty ( ) ) { return initialUrl ; } val mappings = getAuthenticationContextMappings ( ) ; val p = authnRequest . getRequestedAuthnContext ( ) . getAuthnContextClassRefs ( ) . stream ( ) . filter ( ref -> { val clazz = ref . getAuthnContextClassRef ( ) ; return mappings . containsKey ( clazz ) ; } ) . findFirst ( ) ; if ( p . isPresent ( ) ) { val mappedClazz = mappings . get ( p . get ( ) . getAuthnContextClassRef ( ) ) ; return initialUrl + '&' + samlProfileHandlerConfigurationContext . getCasProperties ( ) . getAuthn ( ) . getMfa ( ) . getRequestParameter ( ) + '=' + mappedClazz ; } return initialUrl ; }
Build redirect url by requested authn context .
18,446
protected void initiateAuthenticationRequest ( final Pair < ? extends SignableSAMLObject , MessageContext > pair , final HttpServletResponse response , final HttpServletRequest request ) throws Exception { verifySamlAuthenticationRequest ( pair , request ) ; issueAuthenticationRequestRedirect ( pair , request , response ) ; }
Initiate authentication request .
18,447
protected Pair < SamlRegisteredService , SamlRegisteredServiceServiceProviderMetadataFacade > verifySamlAuthenticationRequest ( final Pair < ? extends SignableSAMLObject , MessageContext > authenticationContext , final HttpServletRequest request ) throws Exception { val authnRequest = ( AuthnRequest ) authenticationContext . getKey ( ) ; val issuer = SamlIdPUtils . getIssuerFromSamlObject ( authnRequest ) ; LOGGER . debug ( "Located issuer [{}] from authentication request" , issuer ) ; val registeredService = verifySamlRegisteredService ( issuer ) ; LOGGER . debug ( "Fetching saml metadata adaptor for [{}]" , issuer ) ; val adaptor = SamlRegisteredServiceServiceProviderMetadataFacade . get ( samlProfileHandlerConfigurationContext . getSamlRegisteredServiceCachingMetadataResolver ( ) , registeredService , authnRequest ) ; if ( adaptor . isEmpty ( ) ) { LOGGER . warn ( "No metadata could be found for [{}]" , issuer ) ; throw new UnauthorizedServiceException ( UnauthorizedServiceException . CODE_UNAUTHZ_SERVICE , "Cannot find metadata linked to " + issuer ) ; } val facade = adaptor . get ( ) ; verifyAuthenticationContextSignature ( authenticationContext , request , authnRequest , facade ) ; SamlUtils . logSamlObject ( samlProfileHandlerConfigurationContext . getOpenSamlConfigBean ( ) , authnRequest ) ; return Pair . of ( registeredService , facade ) ; }
Verify saml authentication request .
18,448
protected void buildSamlResponse ( final HttpServletResponse response , final HttpServletRequest request , final Pair < AuthnRequest , MessageContext > authenticationContext , final Assertion casAssertion , final String binding ) { val authnRequest = authenticationContext . getKey ( ) ; val pair = getRegisteredServiceAndFacade ( authnRequest ) ; val entityId = pair . getValue ( ) . getEntityId ( ) ; LOGGER . debug ( "Preparing SAML response for [{}]" , entityId ) ; samlProfileHandlerConfigurationContext . getResponseBuilder ( ) . build ( authnRequest , request , response , casAssertion , pair . getKey ( ) , pair . getValue ( ) , binding , authenticationContext . getValue ( ) ) ; LOGGER . info ( "Built the SAML response for [{}]" , entityId ) ; }
Build saml response .
18,449
protected Pair < SamlRegisteredService , SamlRegisteredServiceServiceProviderMetadataFacade > getRegisteredServiceAndFacade ( final AuthnRequest request ) { val issuer = SamlIdPUtils . getIssuerFromSamlObject ( request ) ; LOGGER . debug ( "Located issuer [{}] from authentication context" , issuer ) ; val registeredService = verifySamlRegisteredService ( issuer ) ; LOGGER . debug ( "Located SAML metadata for [{}]" , registeredService . getServiceId ( ) ) ; val adaptor = getSamlMetadataFacadeFor ( registeredService , request ) ; if ( adaptor . isEmpty ( ) ) { throw new UnauthorizedServiceException ( UnauthorizedServiceException . CODE_UNAUTHZ_SERVICE , "Cannot find metadata linked to " + issuer ) ; } val facade = adaptor . get ( ) ; return Pair . of ( registeredService , facade ) ; }
Gets registered service and facade .
18,450
protected MessageContext decodeSoapRequest ( final HttpServletRequest request ) { try { val decoder = new HTTPSOAP11Decoder ( ) ; decoder . setParserPool ( samlProfileHandlerConfigurationContext . getOpenSamlConfigBean ( ) . getParserPool ( ) ) ; decoder . setHttpServletRequest ( request ) ; val binding = new BindingDescriptor ( ) ; binding . setId ( getClass ( ) . getName ( ) ) ; binding . setShortName ( getClass ( ) . getName ( ) ) ; binding . setSignatureCapable ( true ) ; binding . setSynchronous ( true ) ; decoder . setBindingDescriptor ( binding ) ; decoder . initialize ( ) ; decoder . decode ( ) ; return decoder . getMessageContext ( ) ; } catch ( final Exception e ) { LOGGER . error ( e . getMessage ( ) , e ) ; } return null ; }
Decode soap 11 context .
18,451
private int deleteTicketGrantingTickets ( final String ticketId ) { var totalCount = 0 ; val st = this . ticketCatalog . find ( ServiceTicket . PREFIX ) ; val sql1 = String . format ( "delete from %s s where s.ticketGrantingTicket.id = :id" , getTicketEntityName ( st ) ) ; var query = entityManager . createQuery ( sql1 ) ; query . setParameter ( "id" , ticketId ) ; totalCount += query . executeUpdate ( ) ; val tgt = this . ticketCatalog . find ( TicketGrantingTicket . PREFIX ) ; val sql2 = String . format ( "delete from %s s where s.ticketGrantingTicket.id = :id" , getTicketEntityName ( tgt ) ) ; query = entityManager . createQuery ( sql2 ) ; query . setParameter ( "id" , ticketId ) ; totalCount += query . executeUpdate ( ) ; val sql3 = String . format ( "delete from %s t where t.id = :id" , getTicketEntityName ( tgt ) ) ; query = entityManager . createQuery ( sql3 ) ; query . setParameter ( "id" , ticketId ) ; totalCount += query . executeUpdate ( ) ; return totalCount ; }
Delete ticket granting tickets int .
18,452
@ GetMapping ( produces = MediaType . APPLICATION_JSON_VALUE ) public ResponseEntity ssoStatus ( final HttpServletRequest request ) { val tgtId = this . ticketGrantingTicketCookieGenerator . retrieveCookieValue ( request ) ; if ( StringUtils . isNotBlank ( tgtId ) ) { val auth = this . ticketRegistrySupport . getAuthenticationFrom ( tgtId ) ; if ( auth != null ) { val ticketState = this . ticketRegistrySupport . getTicketState ( tgtId ) ; val body = CollectionUtils . wrap ( "principal" , auth . getPrincipal ( ) . getId ( ) , "authenticationDate" , auth . getAuthenticationDate ( ) , "ticketGrantingTicketCreationTime" , ticketState . getCreationTime ( ) , "ticketGrantingTicketPreviousTimeUsed" , ticketState . getPreviousTimeUsed ( ) , "ticketGrantingTicketLastTimeUsed" , ticketState . getLastTimeUsed ( ) ) ; return ResponseEntity . ok ( body ) ; } } return ResponseEntity . badRequest ( ) . build ( ) ; }
Sso status response entity .
18,453
public static Pair < Boolean , Optional < Map < String , Object > > > authenticate ( final String username , final String password , final List < RadiusServer > servers , final boolean failoverOnAuthenticationFailure , final boolean failoverOnException , final Optional state ) throws Exception { for ( val radiusServer : servers ) { LOGGER . debug ( "Attempting to authenticate [{}] at [{}]" , username , radiusServer ) ; try { val response = radiusServer . authenticate ( username , password , state ) ; if ( response != null ) { val attributes = new HashMap < String , Object > ( ) ; response . getAttributes ( ) . forEach ( attribute -> attributes . put ( attribute . getAttributeName ( ) , attribute . getValue ( ) ) ) ; return Pair . of ( Boolean . TRUE , Optional . of ( attributes ) ) ; } if ( ! failoverOnAuthenticationFailure ) { throw new FailedLoginException ( "Radius authentication failed for user " + username ) ; } LOGGER . debug ( "failoverOnAuthenticationFailure enabled -- trying next server" ) ; } catch ( final Exception e ) { if ( ! failoverOnException ) { throw e ; } LOGGER . warn ( "failoverOnException enabled -- trying next server." , e ) ; } } return Pair . of ( Boolean . FALSE , Optional . empty ( ) ) ; }
Authenticate pair .
18,454
@ ShellMethod ( key = "find" , value = "Look up properties associated with a CAS group/module." ) public void find ( @ ShellOption ( value = { "name" } , help = "Property name regex pattern" , defaultValue = ".+" ) final String name , @ ShellOption ( value = { "strict-match" } , help = "Whether pattern should be done in strict-mode which means " + "the matching engine tries to match the entire region for the query." ) final boolean strict , @ ShellOption ( value = { "summary" } , help = "Whether results should be presented in summarized mode" ) final boolean summary ) { val results = find ( strict , RegexUtils . createPattern ( name ) ) ; if ( results . isEmpty ( ) ) { LOGGER . info ( "Could not find any results matching the criteria" ) ; return ; } results . forEach ( ( k , v ) -> { if ( summary ) { LOGGER . info ( "{}={}" , k , v . getDefaultValue ( ) ) ; val value = StringUtils . normalizeSpace ( v . getShortDescription ( ) ) ; if ( StringUtils . isNotBlank ( value ) ) { LOGGER . info ( "{}" , value ) ; } } else { LOGGER . info ( "Property: {}" , k ) ; LOGGER . info ( "Group: {}" , StringUtils . substringBeforeLast ( k , "." ) ) ; LOGGER . info ( "Default Value: {}" , ObjectUtils . defaultIfNull ( v . getDefaultValue ( ) , "[blank]" ) ) ; LOGGER . info ( "Type: {}" , v . getType ( ) ) ; LOGGER . info ( "Summary: {}" , StringUtils . normalizeSpace ( v . getShortDescription ( ) ) ) ; LOGGER . info ( "Description: {}" , StringUtils . normalizeSpace ( v . getDescription ( ) ) ) ; LOGGER . info ( "Deprecated: {}" , BooleanUtils . toStringYesNo ( v . isDeprecated ( ) ) ) ; } LOGGER . info ( "-" . repeat ( SEP_LINE_LENGTH ) ) ; } ) ; }
Find property .
18,455
public Map < String , ConfigurationMetadataProperty > findByProperty ( final String name ) { return find ( false , RegexUtils . createPattern ( name ) ) ; }
Find by group .
18,456
public static PrivateKey extractPrivateKeyFromResource ( final String signingSecretKey ) { LOGGER . debug ( "Attempting to extract private key..." ) ; val resource = ResourceUtils . getResourceFrom ( signingSecretKey ) ; val factory = new PrivateKeyFactoryBean ( ) ; factory . setAlgorithm ( RsaKeyUtil . RSA ) ; factory . setLocation ( resource ) ; factory . setSingleton ( false ) ; return factory . getObject ( ) ; }
Extract private key from resource private key .
18,457
public static PublicKey extractPublicKeyFromResource ( final String secretKeyToUse ) { LOGGER . debug ( "Attempting to extract public key from [{}]..." , secretKeyToUse ) ; val resource = ResourceUtils . getResourceFrom ( secretKeyToUse ) ; val factory = new PublicKeyFactoryBean ( ) ; factory . setAlgorithm ( RsaKeyUtil . RSA ) ; factory . setResource ( resource ) ; factory . setSingleton ( false ) ; return factory . getObject ( ) ; }
Extract public key from resource public key .
18,458
protected byte [ ] sign ( final byte [ ] value ) { if ( this . signingKey == null ) { return value ; } if ( "RSA" . equalsIgnoreCase ( this . signingKey . getAlgorithm ( ) ) ) { return EncodingUtils . signJwsRSASha512 ( this . signingKey , value ) ; } return EncodingUtils . signJwsHMACSha512 ( this . signingKey , value ) ; }
Sign the array by first turning it into a base64 encoded string .
18,459
protected void configureSigningKey ( final String signingSecretKey ) { try { if ( ResourceUtils . doesResourceExist ( signingSecretKey ) ) { configureSigningKeyFromPrivateKeyResource ( signingSecretKey ) ; } } finally { if ( this . signingKey == null ) { setSigningKey ( new AesKey ( signingSecretKey . getBytes ( StandardCharsets . UTF_8 ) ) ) ; LOGGER . trace ( "Created signing key instance [{}] based on provided secret key" , this . signingKey . getClass ( ) . getSimpleName ( ) ) ; } } }
Sets signing key . If the key provided is resolved as a private key then will create use the private key as is and will sign values using RSA . Otherwise AES is used .
18,460
protected void configureSigningKeyFromPrivateKeyResource ( final String signingSecretKey ) { val object = extractPrivateKeyFromResource ( signingSecretKey ) ; LOGGER . trace ( "Located signing key resource [{}]" , signingSecretKey ) ; setSigningKey ( object ) ; }
Configure signing key from private key resource .
18,461
protected OAuth20TokenGeneratedResult generateAccessTokenOAuthDeviceCodeResponseType ( final AccessTokenRequestDataHolder holder ) { val deviceCode = holder . getDeviceCode ( ) ; if ( StringUtils . isNotBlank ( deviceCode ) ) { val deviceCodeTicket = getDeviceTokenFromTicketRegistry ( deviceCode ) ; val deviceUserCode = getDeviceUserCodeFromRegistry ( deviceCodeTicket ) ; if ( deviceUserCode . isUserCodeApproved ( ) ) { LOGGER . debug ( "Provided user code [{}] linked to device code [{}] is approved" , deviceCodeTicket . getId ( ) , deviceCode ) ; this . ticketRegistry . deleteTicket ( deviceCode ) ; val deviceResult = AccessTokenRequestDataHolder . builder ( ) . service ( holder . getService ( ) ) . authentication ( holder . getAuthentication ( ) ) . registeredService ( holder . getRegisteredService ( ) ) . ticketGrantingTicket ( holder . getTicketGrantingTicket ( ) ) . grantType ( holder . getGrantType ( ) ) . scopes ( new LinkedHashSet < > ( ) ) . responseType ( holder . getResponseType ( ) ) . generateRefreshToken ( holder . getRegisteredService ( ) != null && holder . isGenerateRefreshToken ( ) ) . build ( ) ; val ticketPair = generateAccessTokenOAuthGrantTypes ( deviceResult ) ; return generateAccessTokenResult ( deviceResult , ticketPair ) ; } if ( deviceCodeTicket . getLastTimeUsed ( ) != null ) { val interval = Beans . newDuration ( casProperties . getAuthn ( ) . getOauth ( ) . getDeviceToken ( ) . getRefreshInterval ( ) ) . getSeconds ( ) ; val shouldSlowDown = deviceCodeTicket . getLastTimeUsed ( ) . plusSeconds ( interval ) . isAfter ( ZonedDateTime . now ( ZoneOffset . UTC ) ) ; if ( shouldSlowDown ) { LOGGER . error ( "Request for user code approval is greater than the configured refresh interval of [{}] second(s)" , interval ) ; throw new ThrottledOAuth20DeviceUserCodeApprovalException ( deviceCodeTicket . getId ( ) ) ; } } deviceCodeTicket . update ( ) ; this . ticketRegistry . updateTicket ( deviceCodeTicket ) ; LOGGER . error ( "Provided user code [{}] linked to device code [{}] is NOT approved yet" , deviceCodeTicket . getId ( ) , deviceCode ) ; throw new UnapprovedOAuth20DeviceUserCodeException ( deviceCodeTicket . getId ( ) ) ; } val deviceTokens = createDeviceTokensInTicketRegistry ( holder ) ; return OAuth20TokenGeneratedResult . builder ( ) . responseType ( holder . getResponseType ( ) ) . registeredService ( holder . getRegisteredService ( ) ) . deviceCode ( deviceTokens . getLeft ( ) . getId ( ) ) . userCode ( deviceTokens . getValue ( ) . getId ( ) ) . build ( ) ; }
Generate access token OAuth device code response type OAuth token generated result .
18,462
protected Pair < AccessToken , RefreshToken > generateAccessTokenOAuthGrantTypes ( final AccessTokenRequestDataHolder holder ) { LOGGER . debug ( "Creating access token for [{}]" , holder . getService ( ) ) ; val clientId = holder . getRegisteredService ( ) . getClientId ( ) ; val authn = DefaultAuthenticationBuilder . newInstance ( holder . getAuthentication ( ) ) . addAttribute ( OAuth20Constants . GRANT_TYPE , holder . getGrantType ( ) . toString ( ) ) . addAttribute ( OAuth20Constants . SCOPE , holder . getScopes ( ) ) . addAttribute ( OAuth20Constants . CLIENT_ID , clientId ) . build ( ) ; LOGGER . debug ( "Creating access token for [{}]" , holder ) ; val ticketGrantingTicket = holder . getTicketGrantingTicket ( ) ; val accessToken = this . accessTokenFactory . create ( holder . getService ( ) , authn , ticketGrantingTicket , holder . getScopes ( ) , clientId ) ; LOGGER . debug ( "Created access token [{}]" , accessToken ) ; addTicketToRegistry ( accessToken , ticketGrantingTicket ) ; LOGGER . debug ( "Added access token [{}] to registry" , accessToken ) ; updateOAuthCode ( holder ) ; val refreshToken = FunctionUtils . doIf ( holder . isGenerateRefreshToken ( ) , ( ) -> generateRefreshToken ( holder ) , ( ) -> { LOGGER . debug ( "Service [{}] is not able/allowed to receive refresh tokens" , holder . getService ( ) ) ; return null ; } ) . get ( ) ; return Pair . of ( accessToken , refreshToken ) ; }
Generate access token OAuth grant types pair .
18,463
protected void updateOAuthCode ( final AccessTokenRequestDataHolder holder ) { if ( holder . getToken ( ) instanceof OAuthCode ) { val codeState = TicketState . class . cast ( holder . getToken ( ) ) ; codeState . update ( ) ; if ( holder . getToken ( ) . isExpired ( ) ) { this . ticketRegistry . deleteTicket ( holder . getToken ( ) . getId ( ) ) ; } else { this . ticketRegistry . updateTicket ( holder . getToken ( ) ) ; } this . ticketRegistry . updateTicket ( holder . getTicketGrantingTicket ( ) ) ; } }
Update OAuth code .
18,464
protected void addTicketToRegistry ( final Ticket ticket , final TicketGrantingTicket ticketGrantingTicket ) { LOGGER . debug ( "Adding ticket [{}] to registry" , ticket ) ; this . ticketRegistry . addTicket ( ticket ) ; if ( ticketGrantingTicket != null ) { LOGGER . debug ( "Updating parent ticket-granting ticket [{}]" , ticketGrantingTicket ) ; this . ticketRegistry . updateTicket ( ticketGrantingTicket ) ; } }
Add ticket to registry .
18,465
protected RefreshToken generateRefreshToken ( final AccessTokenRequestDataHolder responseHolder ) { LOGGER . debug ( "Creating refresh token for [{}]" , responseHolder . getService ( ) ) ; val refreshToken = this . refreshTokenFactory . create ( responseHolder . getService ( ) , responseHolder . getAuthentication ( ) , responseHolder . getTicketGrantingTicket ( ) , responseHolder . getScopes ( ) , responseHolder . getClientId ( ) ) ; LOGGER . debug ( "Adding refresh token [{}] to the registry" , refreshToken ) ; addTicketToRegistry ( refreshToken , responseHolder . getTicketGrantingTicket ( ) ) ; return refreshToken ; }
Generate refresh token .
18,466
protected Event grantTicketGrantingTicketToAuthenticationResult ( final RequestContext context , final AuthenticationResultBuilder authenticationResultBuilder , final Service service ) { WebUtils . putAuthenticationResultBuilder ( authenticationResultBuilder , context ) ; WebUtils . putServiceIntoFlowScope ( context , service ) ; return newEvent ( CasWebflowConstants . TRANSITION_ID_SUCCESS ) ; }
Grant ticket granting ticket .
18,467
protected void putResolvedEventsAsAttribute ( final RequestContext context , final Set < Event > resolvedEvents ) { context . getAttributes ( ) . put ( RESOLVED_AUTHENTICATION_EVENTS , resolvedEvents ) ; }
Put resolved events as attribute .
18,468
protected Service resolveServiceFromAuthenticationRequest ( final RequestContext context ) { val ctxService = WebUtils . getService ( context ) ; return resolveServiceFromAuthenticationRequest ( ctxService ) ; }
Resolve service from authentication request service .
18,469
protected Set < Event > getResolvedEventsAsAttribute ( final RequestContext context ) { return context . getAttributes ( ) . get ( RESOLVED_AUTHENTICATION_EVENTS , Set . class ) ; }
Gets resolved events as attribute .
18,470
protected Set < Event > handleAuthenticationTransactionAndGrantTicketGrantingTicket ( final RequestContext context ) { val response = WebUtils . getHttpServletResponseFromExternalWebflowContext ( context ) ; try { val credential = getCredentialFromContext ( context ) ; val builderResult = WebUtils . getAuthenticationResultBuilder ( context ) ; LOGGER . debug ( "Handling authentication transaction for credential [{}]" , credential ) ; val service = WebUtils . getService ( context ) ; val builder = webflowEventResolutionConfigurationContext . getAuthenticationSystemSupport ( ) . handleAuthenticationTransaction ( service , builderResult , credential ) ; LOGGER . debug ( "Issuing ticket-granting tickets for service [{}]" , service ) ; return CollectionUtils . wrapSet ( grantTicketGrantingTicketToAuthenticationResult ( context , builder , service ) ) ; } catch ( final Exception e ) { LOGGER . error ( e . getMessage ( ) , e ) ; val messageContext = context . getMessageContext ( ) ; messageContext . addMessage ( new MessageBuilder ( ) . error ( ) . code ( DEFAULT_MESSAGE_BUNDLE_PREFIX . concat ( e . getClass ( ) . getSimpleName ( ) ) ) . build ( ) ) ; response . setStatus ( HttpStatus . UNAUTHORIZED . value ( ) ) ; return CollectionUtils . wrapSet ( getAuthenticationFailureErrorEvent ( context ) ) ; } }
Handle authentication transaction and grant ticket granting ticket .
18,471
protected Set < Event > handlePossibleSuspiciousAttempt ( final HttpServletRequest request , final Authentication authentication , final RegisteredService service ) { getWebflowEventResolutionConfigurationContext ( ) . getEventPublisher ( ) . publishEvent ( new CasRiskBasedAuthenticationEvaluationStartedEvent ( this , authentication , service ) ) ; LOGGER . debug ( "Evaluating possible suspicious authentication attempt for [{}]" , authentication . getPrincipal ( ) ) ; val score = authenticationRiskEvaluator . eval ( authentication , service , request ) ; if ( score . isRiskGreaterThan ( threshold ) ) { getWebflowEventResolutionConfigurationContext ( ) . getEventPublisher ( ) . publishEvent ( new CasRiskyAuthenticationDetectedEvent ( this , authentication , service , score ) ) ; LOGGER . debug ( "Calculated risk score [{}] for authentication request by [{}] is above the risk threshold [{}]." , score . getScore ( ) , authentication . getPrincipal ( ) , threshold ) ; getWebflowEventResolutionConfigurationContext ( ) . getEventPublisher ( ) . publishEvent ( new CasRiskBasedAuthenticationMitigationStartedEvent ( this , authentication , service , score ) ) ; val res = authenticationRiskMitigator . mitigate ( authentication , service , score , request ) ; getWebflowEventResolutionConfigurationContext ( ) . getEventPublisher ( ) . publishEvent ( new CasRiskyAuthenticationMitigatedEvent ( this , authentication , service , res ) ) ; return CollectionUtils . wrapSet ( res . getResult ( ) ) ; } LOGGER . debug ( "Authentication request for [{}] is below the risk threshold" , authentication . getPrincipal ( ) ) ; return null ; }
Handle possible suspicious attempt .
18,472
protected Principal createPrincipal ( final String username , final LdapEntry ldapEntry ) throws LoginException { LOGGER . debug ( "Creating LDAP principal for [{}] based on [{}] and attributes [{}]" , username , ldapEntry . getDn ( ) , ldapEntry . getAttributeNames ( ) ) ; val id = getLdapPrincipalIdentifier ( username , ldapEntry ) ; LOGGER . debug ( "LDAP principal identifier created is [{}]" , id ) ; val attributeMap = collectAttributesForLdapEntry ( ldapEntry , id ) ; LOGGER . debug ( "Created LDAP principal for id [{}] and [{}] attributes" , id , attributeMap . size ( ) ) ; return this . principalFactory . createPrincipal ( id , attributeMap ) ; }
Creates a CAS principal with attributes if the LDAP entry contains principal attributes .
18,473
protected Map < String , List < Object > > collectAttributesForLdapEntry ( final LdapEntry ldapEntry , final String username ) { val attributeMap = Maps . < String , List < Object > > newHashMapWithExpectedSize ( this . principalAttributeMap . size ( ) ) ; LOGGER . debug ( "The following attributes are requested to be retrieved and mapped: [{}]" , attributeMap . keySet ( ) ) ; this . principalAttributeMap . forEach ( ( key , attributeNames ) -> { val attr = ldapEntry . getAttribute ( key ) ; if ( attr != null ) { LOGGER . debug ( "Found principal attribute: [{}]" , attr ) ; val names = ( Collection < String > ) attributeNames ; if ( names . isEmpty ( ) ) { LOGGER . debug ( "Principal attribute [{}] is collected as [{}]" , attr , key ) ; attributeMap . put ( key , CollectionUtils . wrap ( attr . getStringValues ( ) ) ) ; } else { names . forEach ( s -> { LOGGER . debug ( "Principal attribute [{}] is virtually remapped/renamed to [{}]" , attr , s ) ; attributeMap . put ( s , CollectionUtils . wrap ( attr . getStringValues ( ) ) ) ; } ) ; } } else { LOGGER . warn ( "Requested LDAP attribute [{}] could not be found on the resolved LDAP entry for [{}]" , key , ldapEntry . getDn ( ) ) ; } } ) ; if ( this . collectDnAttribute ) { LOGGER . debug ( "Recording principal DN attribute as [{}]" , this . principalDnAttributeName ) ; attributeMap . put ( this . principalDnAttributeName , CollectionUtils . wrapList ( ldapEntry . getDn ( ) ) ) ; } return attributeMap ; }
Collect attributes for ldap entry .
18,474
protected String getLdapPrincipalIdentifier ( final String username , final LdapEntry ldapEntry ) throws LoginException { if ( StringUtils . isNotBlank ( this . principalIdAttribute ) ) { val principalAttr = ldapEntry . getAttribute ( this . principalIdAttribute ) ; if ( principalAttr == null || principalAttr . size ( ) == 0 ) { if ( this . allowMissingPrincipalAttributeValue ) { LOGGER . warn ( "The principal id attribute [{}] is not found. CAS cannot construct the final authenticated principal " + "if it's unable to locate the attribute that is designated as the principal id. " + "Attributes available on the LDAP entry are [{}]. Since principal id attribute is not available, CAS will " + "fall back to construct the principal based on the provided user id: [{}]" , this . principalIdAttribute , ldapEntry . getAttributes ( ) , username ) ; return username ; } LOGGER . error ( "The principal id attribute [{}] is not found. CAS is configured to disallow missing principal attributes" , this . principalIdAttribute ) ; throw new LoginException ( "Principal id attribute is not found for " + principalAttr ) ; } val value = principalAttr . getStringValue ( ) ; if ( principalAttr . size ( ) > 1 ) { if ( ! this . allowMultiplePrincipalAttributeValues ) { throw new LoginException ( "Multiple principal values are not allowed: " + principalAttr ) ; } LOGGER . warn ( "Found multiple values for principal id attribute: [{}]. Using first value=[{}]." , principalAttr , value ) ; } LOGGER . debug ( "Retrieved principal id attribute [{}]" , value ) ; return value ; } LOGGER . debug ( "Principal id attribute is not defined. Using the default provided user id [{}]" , username ) ; return username ; }
Gets ldap principal identifier . If the principal id attribute is defined it s retrieved . If no attribute value is found a warning is generated and the provided username is used instead . If no attribute is defined username is used instead .
18,475
public void initialize ( ) { val attributes = new HashSet < String > ( ) ; LOGGER . debug ( "Initializing LDAP attribute configuration..." ) ; if ( StringUtils . isNotBlank ( this . principalIdAttribute ) ) { LOGGER . debug ( "Configured to retrieve principal id attribute [{}]" , this . principalIdAttribute ) ; attributes . add ( this . principalIdAttribute ) ; } if ( this . principalAttributeMap != null && ! this . principalAttributeMap . isEmpty ( ) ) { val attrs = this . principalAttributeMap . keySet ( ) ; attributes . addAll ( attrs ) ; LOGGER . debug ( "Configured to retrieve principal attribute collection of [{}]" , attrs ) ; } if ( authenticator . getReturnAttributes ( ) != null ) { val authenticatorAttributes = CollectionUtils . wrapList ( authenticator . getReturnAttributes ( ) ) ; if ( ! authenticatorAttributes . isEmpty ( ) ) { LOGGER . debug ( "Filtering authentication entry attributes [{}] based on authenticator attributes [{}]" , authenticatedEntryAttributes , authenticatorAttributes ) ; attributes . removeIf ( authenticatorAttributes :: contains ) ; } } this . authenticatedEntryAttributes = attributes . toArray ( ArrayUtils . EMPTY_STRING_ARRAY ) ; LOGGER . debug ( "LDAP authentication entry attributes for the authentication request are [{}]" , ( Object [ ] ) this . authenticatedEntryAttributes ) ; }
Initialize the handler setup the authentication entry attributes .
18,476
protected List < String > resolveEventFromHttpRequest ( final HttpServletRequest request ) { val mfaRequestHeader = casProperties . getAuthn ( ) . getMfa ( ) . getRequestHeader ( ) ; val headers = request . getHeaders ( mfaRequestHeader ) ; if ( headers != null && headers . hasMoreElements ( ) ) { LOGGER . debug ( "Received request header [{}] as [{}]" , mfaRequestHeader , headers ) ; return Collections . list ( headers ) ; } val mfaRequestParameter = casProperties . getAuthn ( ) . getMfa ( ) . getRequestParameter ( ) ; val params = request . getParameterValues ( mfaRequestParameter ) ; if ( params != null && params . length > 0 ) { LOGGER . debug ( "Received request parameter [{}] as [{}]" , mfaRequestParameter , params ) ; return Arrays . stream ( params ) . collect ( Collectors . toList ( ) ) ; } val attributeName = casProperties . getAuthn ( ) . getMfa ( ) . getSessionAttribute ( ) ; val session = request . getSession ( false ) ; var attributeValue = session != null ? session . getAttribute ( attributeName ) : null ; if ( attributeValue == null ) { LOGGER . trace ( "No value could be found for session attribute [{}]. Checking request attributes..." , attributeName ) ; attributeValue = request . getAttribute ( attributeName ) ; } if ( attributeValue == null ) { LOGGER . trace ( "No value could be found for [{}]" , attributeName ) ; return null ; } val values = CollectionUtils . toCollection ( attributeValue ) ; LOGGER . debug ( "Found values [{}] mapped to attribute name [{}]" , values , attributeName ) ; return values . stream ( ) . map ( Object :: toString ) . collect ( Collectors . toList ( ) ) ; }
Resolve event from http request .
18,477
protected void doPublishEvent ( final ApplicationEvent e ) { if ( applicationEventPublisher != null ) { LOGGER . trace ( "Publishing [{}]" , e ) ; this . applicationEventPublisher . publishEvent ( e ) ; } }
Publish CAS events .
18,478
protected Authentication getAuthenticationSatisfiedByPolicy ( final Authentication authentication , final ServiceContext context ) throws AbstractTicketException { val policy = this . serviceContextAuthenticationPolicyFactory . createPolicy ( context ) ; try { if ( policy . isSatisfiedBy ( authentication ) ) { return authentication ; } } catch ( final Exception e ) { LOGGER . error ( e . getMessage ( ) , e ) ; } throw new UnsatisfiedAuthenticationPolicyException ( policy ) ; }
Gets the authentication satisfied by policy .
18,479
protected void evaluateProxiedServiceIfNeeded ( final Service service , final TicketGrantingTicket ticketGrantingTicket , final RegisteredService registeredService ) { val proxiedBy = ticketGrantingTicket . getProxiedBy ( ) ; if ( proxiedBy != null ) { LOGGER . debug ( "Ticket-granting ticket is proxied by [{}]. Locating proxy service in registry..." , proxiedBy . getId ( ) ) ; val proxyingService = this . servicesManager . findServiceBy ( proxiedBy ) ; if ( proxyingService != null ) { LOGGER . debug ( "Located proxying service [{}] in the service registry" , proxyingService ) ; if ( ! proxyingService . getProxyPolicy ( ) . isAllowedToProxy ( ) ) { LOGGER . warn ( "Found proxying service [{}], but it is not authorized to fulfill the proxy attempt made by [{}]" , proxyingService . getId ( ) , service . getId ( ) ) ; throw new UnauthorizedProxyingException ( UnauthorizedProxyingException . MESSAGE + registeredService . getId ( ) ) ; } } else { LOGGER . warn ( "No proxying service found. Proxy attempt by service [{}] (registered service [{}]) is not allowed." , service . getId ( ) , registeredService . getId ( ) ) ; throw new UnauthorizedProxyingException ( UnauthorizedProxyingException . MESSAGE + registeredService . getId ( ) ) ; } } else { LOGGER . trace ( "Ticket-granting ticket is not proxied by another service" ) ; } }
Evaluate proxied service if needed .
18,480
protected void verifyTicketState ( final Ticket ticket , final String id , final Class clazz ) { if ( ticket == null ) { LOGGER . debug ( "Ticket [{}] by type [{}] cannot be found in the ticket registry." , id , clazz != null ? clazz . getSimpleName ( ) : "unspecified" ) ; throw new InvalidTicketException ( id ) ; } if ( ticket . isExpired ( ) ) { deleteTicket ( id ) ; LOGGER . debug ( "Ticket [{}] has expired and is now deleted from the ticket registry." , ticket ) ; throw new InvalidTicketException ( id ) ; } }
Validate ticket expiration policy and throws exception if ticket is no longer valid . Expired tickets are also deleted from the registry immediately on demand .
18,481
protected boolean isTicketAuthenticityVerified ( final String ticketId ) { if ( this . cipherExecutor != null ) { LOGGER . trace ( "Attempting to decode service ticket [{}] to verify authenticity" , ticketId ) ; return ! StringUtils . isEmpty ( this . cipherExecutor . decode ( ticketId ) ) ; } return ! StringUtils . isEmpty ( ticketId ) ; }
Verify the ticket id received is actually legitimate before contacting downstream systems to find and process it .
18,482
public static String getDocumentLink ( final String databaseName , final String collectionName , final String documentId ) { return getCollectionLink ( databaseName , collectionName ) + "/docs/" + documentId ; }
Gets document link .
18,483
public DocumentClient createDocumentClient ( final BaseCosmosDbProperties properties ) { val policy = ConnectionPolicy . GetDefault ( ) ; var userAgent = ( policy . getUserAgentSuffix ( ) == null ? StringUtils . EMPTY : ';' + policy . getUserAgentSuffix ( ) ) + ';' + USER_AGENT_SUFFIX ; if ( properties . isAllowTelemetry ( ) && GetHashMac . getHashMac ( ) != null ) { userAgent += ';' + GetHashMac . getHashMac ( ) ; } policy . setUserAgentSuffix ( userAgent ) ; return new DocumentClient ( properties . getUri ( ) , properties . getKey ( ) , policy , ConsistencyLevel . valueOf ( properties . getConsistencyLevel ( ) ) ) ; }
Create document client .
18,484
public DocumentDbFactory createDocumentDbFactory ( final BaseCosmosDbProperties properties ) { val documentClient = createDocumentClient ( properties ) ; return new DocumentDbFactory ( documentClient ) ; }
Create document db factory .
18,485
public DocumentDbTemplate createDocumentDbTemplate ( final DocumentDbFactory documentDbFactory , final BaseCosmosDbProperties properties ) { val documentDbMappingContext = createDocumentDbMappingContext ( ) ; val mappingDocumentDbConverter = createMappingDocumentDbConverter ( documentDbMappingContext ) ; return new DocumentDbTemplate ( documentDbFactory , mappingDocumentDbConverter , properties . getDatabase ( ) ) ; }
Create document db template document db template .
18,486
public DocumentDbMappingContext createDocumentDbMappingContext ( ) { val documentDbMappingContext = new DocumentDbMappingContext ( ) ; documentDbMappingContext . setInitialEntitySet ( new EntityScanner ( applicationContext ) . scan ( Persistent . class ) ) ; return documentDbMappingContext ; }
Create document db mapping context .
18,487
private static String findCurrentClientName ( final J2EContext webContext ) { val pm = new ProfileManager < > ( webContext , webContext . getSessionStore ( ) ) ; val profile = pm . get ( true ) ; return profile . map ( CommonProfile :: getClientName ) . orElse ( null ) ; }
Finds the current client name from the context using the PAC4J Profile Manager . It is assumed that the context has previously been populated with the profile .
18,488
protected void finalizeSamlResponse ( final HttpServletRequest request , final HttpServletResponse response , final String serviceId , final Response samlResponse ) throws Exception { if ( request != null && response != null ) { LOGGER . debug ( "Starting to encode SAML response for service [{}]" , serviceId ) ; this . samlResponseBuilder . encodeSamlResponse ( samlResponse , request , response ) ; } }
Finalize saml response .
18,489
public static JoinPoint unWrapJoinPoint ( final JoinPoint point ) { var naked = point ; while ( naked . getArgs ( ) != null && naked . getArgs ( ) . length > 0 && naked . getArgs ( ) [ 0 ] instanceof JoinPoint ) { naked = ( JoinPoint ) naked . getArgs ( ) [ 0 ] ; } return naked ; }
Unwraps a join point that may be nested due to layered proxies .
18,490
protected void doHealthCheck ( final Health . Builder builder ) { val samlServices = servicesManager . findServiceBy ( registeredService -> registeredService instanceof SamlRegisteredService ) ; val availableResolvers = this . metadataResolutionPlan . getRegisteredMetadataResolvers ( ) ; LOGGER . debug ( "There are [{}] metadata resolver(s) available in the chain" , availableResolvers . size ( ) ) ; builder . up ( ) ; samlServices . stream ( ) . map ( SamlRegisteredService . class :: cast ) . forEach ( service -> { val map = new LinkedHashMap < String , Object > ( ) ; map . put ( "name" , service . getName ( ) ) ; map . put ( "id" , service . getId ( ) ) ; map . put ( "metadataLocation" , service . getMetadataLocation ( ) ) ; map . put ( "serviceId" , service . getServiceId ( ) ) ; val available = availableResolvers . stream ( ) . filter ( Objects :: nonNull ) . peek ( r -> LOGGER . debug ( "Checking if metadata resolver [{}] is available for service [{}]" , r . getName ( ) , service . getName ( ) ) ) . anyMatch ( r -> r . isAvailable ( service ) ) ; map . put ( "availability" , BooleanUtils . toStringYesNo ( available ) ) ; builder . withDetail ( service . getName ( ) , map ) ; if ( ! available ) { LOGGER . debug ( "No metadata resolver is available for service [{}]" , service . getName ( ) ) ; builder . down ( ) ; } } ) ; }
Check for availability of metadata sources . Only need 1 valid resolver for metadata to be available .
18,491
protected void addProfileRoles ( final LdapEntry userEntry , final CommonProfile profile , final LdapAttribute attribute , final String prefix ) { addProfileRolesFromAttributes ( profile , attribute , prefix ) ; }
Add profile roles .
18,492
protected void addProfileRolesFromAttributes ( final CommonProfile profile , final LdapAttribute ldapAttribute , final String prefix ) { ldapAttribute . getStringValues ( ) . forEach ( value -> profile . addRole ( prefix . concat ( value . toUpperCase ( ) ) ) ) ; }
Add profile roles from attributes .
18,493
protected String signToken ( final OidcRegisteredService svc , final JsonWebSignature jws ) throws Exception { LOGGER . debug ( "Fetching JSON web key to sign the token for : [{}]" , svc . getClientId ( ) ) ; val jsonWebKey = getJsonWebKeySigningKey ( ) ; LOGGER . debug ( "Found JSON web key to sign the token: [{}]" , jsonWebKey ) ; if ( jsonWebKey . getPrivateKey ( ) == null ) { throw new IllegalArgumentException ( "JSON web key used to sign the token has no associated private key" ) ; } configureJsonWebSignatureForTokenSigning ( svc , jws , jsonWebKey ) ; return jws . getCompactSerialization ( ) ; }
Sign token .
18,494
protected JsonWebKey getJsonWebKeyForEncryption ( final OidcRegisteredService svc ) { LOGGER . debug ( "Service [{}] is set to encrypt tokens" , svc ) ; val jwks = this . serviceJsonWebKeystoreCache . get ( svc ) ; if ( Objects . requireNonNull ( jwks ) . isEmpty ( ) ) { throw new IllegalArgumentException ( "Service " + svc . getServiceId ( ) + " with client id " + svc . getClientId ( ) + " is configured to encrypt tokens, yet no JSON web key is available" ) ; } val jsonWebKey = jwks . get ( ) ; LOGGER . debug ( "Found JSON web key to encrypt the token: [{}]" , jsonWebKey ) ; if ( jsonWebKey . getPublicKey ( ) == null ) { throw new IllegalArgumentException ( "JSON web key used to sign the token has no associated public key" ) ; } return jsonWebKey ; }
Gets json web key for encryption .
18,495
public ObjectPool < MemcachedClientIF > getObjectPool ( ) { val pool = new GenericObjectPool < MemcachedClientIF > ( this ) ; pool . setMaxIdle ( memcachedProperties . getMaxIdle ( ) ) ; pool . setMinIdle ( memcachedProperties . getMinIdle ( ) ) ; pool . setMaxTotal ( memcachedProperties . getMaxTotal ( ) ) ; return pool ; }
Gets object pool .
18,496
public void initialize ( ) { val pair = buildLoggerContext ( environment , resourceLoader ) ; pair . ifPresent ( it -> { this . logConfigurationFile = it . getKey ( ) ; this . loggerContext = it . getValue ( ) ; } ) ; }
Init . Attempts to locate the logging configuration to insert listeners . The log configuration location is pulled directly from the environment given there is not an explicit property mapping for it provided by Boot etc .
18,497
private Set < LoggerConfig > getLoggerConfigurations ( ) { val configuration = this . loggerContext . getConfiguration ( ) ; return new HashSet < > ( configuration . getLoggers ( ) . values ( ) ) ; }
Gets logger configurations .
18,498
public void updateLoggerLevel ( final String loggerName , final String loggerLevel , final boolean additive ) { val loggerConfigs = getLoggerConfigurations ( ) ; loggerConfigs . stream ( ) . filter ( cfg -> cfg . getName ( ) . equals ( loggerName ) ) . forEachOrdered ( cfg -> { cfg . setLevel ( Level . getLevel ( loggerLevel ) ) ; cfg . setAdditive ( additive ) ; } ) ; this . loggerContext . updateLoggers ( ) ; }
Looks up the logger in the logger factory and attempts to find the real logger instance based on the underlying logging framework and retrieve the logger object . Then updates the level . This functionality at this point is heavily dependant on the log4j API .
18,499
@ View ( name = "by_name" , map = "function(doc) { if(doc.name && doc.value) { emit(doc.name, doc) } }" ) public CouchDbSamlMetadataDocument findFirstByName ( final String name ) { val view = createQuery ( "by_name" ) . key ( name ) . limit ( 1 ) ; return db . queryView ( view , CouchDbSamlMetadataDocument . class ) . stream ( ) . findFirst ( ) . orElse ( null ) ; }
Find by name .