idx int64 0 41.2k | question stringlengths 73 5.81k | target stringlengths 5 918 |
|---|---|---|
17,900 | @ ShellMethod ( key = "generate-anonymous-user" , value = "Generate an anonymous (persistent) username identifier" ) public void generateUsername ( @ ShellOption ( value = { "username" } , help = "Authenticated username" ) final String username , @ ShellOption ( value = { "service" } , help = "Service application URL for which CAS may generate the identifier" ) final String service , @ ShellOption ( value = { "salt" } , help = "Salt used to generate and encode the anonymous identifier" ) final String salt ) { val generator = new ShibbolethCompatiblePersistentIdGenerator ( salt ) ; val id = generator . generate ( username , service ) ; LOGGER . info ( "Generated identifier:\n[{}]" , id ) ; } | Generate username . |
17,901 | public void clean ( ) { val now = ZonedDateTime . now ( ) ; LOGGER . debug ( "Starting to clean previously used authenticator tokens from [{}] at [{}]" , this . tokenRepository , now ) ; tokenRepository . clean ( ) ; LOGGER . info ( "Finished cleaning authenticator tokens at [{}]" , now ) ; } | Clean the repository . |
17,902 | protected ModelAndView redirectToApproveView ( final J2EContext ctx , final OAuthRegisteredService svc ) { val callbackUrl = ctx . getFullRequestURL ( ) ; LOGGER . trace ( "callbackUrl: [{}]" , callbackUrl ) ; val url = new URIBuilder ( callbackUrl ) ; url . addParameter ( OAuth20Constants . BYPASS_APPROVAL_PROMPT , Boolean . TRUE . toString ( ) ) ; val model = new HashMap < String , Object > ( ) ; model . put ( "service" , svc ) ; model . put ( "callbackUrl" , url . toString ( ) ) ; model . put ( "serviceName" , svc . getName ( ) ) ; model . put ( "deniedApprovalUrl" , svc . getAccessStrategy ( ) . getUnauthorizedRedirectUrl ( ) ) ; prepareApprovalViewModel ( model , ctx , svc ) ; return getApprovalModelAndView ( model ) ; } | Redirect to approve view model and view . |
17,903 | public static void generateQRCode ( final OutputStream stream , final String key , final int width , final int height ) { val hintMap = new EnumMap < EncodeHintType , Object > ( EncodeHintType . class ) ; hintMap . put ( EncodeHintType . CHARACTER_SET , StandardCharsets . UTF_8 . name ( ) ) ; hintMap . put ( EncodeHintType . MARGIN , 2 ) ; hintMap . put ( EncodeHintType . ERROR_CORRECTION , ErrorCorrectionLevel . L ) ; val qrCodeWriter = new QRCodeWriter ( ) ; val byteMatrix = qrCodeWriter . encode ( key , BarcodeFormat . QR_CODE , width , height , hintMap ) ; val byteMatrixWidth = byteMatrix . getWidth ( ) ; val image = new BufferedImage ( byteMatrixWidth , byteMatrixWidth , BufferedImage . TYPE_INT_RGB ) ; image . createGraphics ( ) ; @ Cleanup ( "dispose" ) val graphics = ( Graphics2D ) image . getGraphics ( ) ; graphics . setColor ( Color . WHITE ) ; graphics . fillRect ( 0 , 0 , byteMatrixWidth , byteMatrixWidth ) ; graphics . setColor ( Color . BLACK ) ; IntStream . range ( 0 , byteMatrixWidth ) . forEach ( i -> IntStream . range ( 0 , byteMatrixWidth ) . filter ( j -> byteMatrix . get ( i , j ) ) . forEach ( j -> graphics . fillRect ( i , j , 1 , 1 ) ) ) ; ImageIO . write ( image , "png" , stream ) ; } | Generate qr code . |
17,904 | protected AuthenticationHandlerExecutionResult createResult ( final ClientCredential credentials , final UserProfile profile , final BaseClient client ) throws GeneralSecurityException { if ( profile == null ) { throw new FailedLoginException ( "Authentication did not produce a user profile for: " + credentials ) ; } val id = determinePrincipalIdFrom ( profile , client ) ; if ( StringUtils . isBlank ( id ) ) { throw new FailedLoginException ( "No identifier found for this user profile: " + profile ) ; } credentials . setUserProfile ( profile ) ; credentials . setTypedIdUsed ( isTypedIdUsed ) ; val attributes = CoreAuthenticationUtils . convertAttributeValuesToMultiValuedObjects ( profile . getAttributes ( ) ) ; val principal = this . principalFactory . createPrincipal ( id , attributes ) ; LOGGER . debug ( "Constructed authenticated principal [{}] based on user profile [{}]" , principal , profile ) ; return finalizeAuthenticationHandlerResult ( credentials , principal , profile , client ) ; } | Build the handler result . |
17,905 | protected AuthenticationHandlerExecutionResult finalizeAuthenticationHandlerResult ( final ClientCredential credentials , final Principal principal , final UserProfile profile , final BaseClient client ) { preFinalizeAuthenticationHandlerResult ( credentials , principal , profile , client ) ; return createHandlerResult ( credentials , principal , new ArrayList < > ( 0 ) ) ; } | Finalize authentication handler result . |
17,906 | protected String determinePrincipalIdFrom ( final UserProfile profile , final BaseClient client ) { var id = profile . getId ( ) ; val properties = client != null ? client . getCustomProperties ( ) : new HashMap < > ( ) ; if ( client != null && properties . containsKey ( ClientCustomPropertyConstants . CLIENT_CUSTOM_PROPERTY_PRINCIPAL_ATTRIBUTE_ID ) ) { val attrObject = properties . get ( ClientCustomPropertyConstants . CLIENT_CUSTOM_PROPERTY_PRINCIPAL_ATTRIBUTE_ID ) ; if ( attrObject != null ) { val principalAttribute = attrObject . toString ( ) ; if ( profile . containsAttribute ( principalAttribute ) ) { val firstAttribute = CollectionUtils . firstElement ( profile . getAttribute ( principalAttribute ) ) ; if ( firstAttribute . isPresent ( ) ) { id = firstAttribute . get ( ) . toString ( ) ; id = typePrincipalId ( id , profile ) ; } LOGGER . debug ( "Delegated authentication indicates usage of client principal attribute [{}] for the identifier [{}]" , principalAttribute , id ) ; } else { LOGGER . warn ( "Delegated authentication cannot find attribute [{}] to use as principal id" , principalAttribute ) ; } } else { LOGGER . warn ( "No custom principal attribute was provided by the client [{}]. Using the default id [{}]" , client , id ) ; } } else if ( StringUtils . isNotBlank ( principalAttributeId ) ) { if ( profile . containsAttribute ( principalAttributeId ) ) { val firstAttribute = CollectionUtils . firstElement ( profile . getAttribute ( principalAttributeId ) ) ; if ( firstAttribute . isPresent ( ) ) { id = firstAttribute . get ( ) . toString ( ) ; id = typePrincipalId ( id , profile ) ; } } else { LOGGER . warn ( "CAS cannot use [{}] as the principal attribute id, since the profile attributes do not contain the attribute. " + "Either adjust the CAS configuration to use a different attribute, or contact the delegated authentication provider noted by [{}] " + "to release the expected attribute to CAS" , principalAttributeId , profile . getAttributes ( ) ) ; } LOGGER . debug ( "Delegated authentication indicates usage of attribute [{}] for the identifier [{}]" , principalAttributeId , id ) ; } else if ( isTypedIdUsed ) { id = profile . getTypedId ( ) ; LOGGER . debug ( "Delegated authentication indicates usage of typed profile id [{}]" , id ) ; } LOGGER . debug ( "Final principal id determined based on client [{}] and user profile [{}] is [{}]" , profile , client , id ) ; return id ; } | Determine principal id from profile . |
17,907 | protected void validateCredentials ( final UsernamePasswordCredentials credentials , final OAuthRegisteredService registeredService , final WebContext context ) { if ( ! OAuth20Utils . checkClientSecret ( registeredService , credentials . getPassword ( ) ) ) { throw new CredentialsException ( "Bad secret for client identifier: " + credentials . getPassword ( ) ) ; } } | Validate credentials . |
17,908 | protected String buildSingleAttributeDefinitionLine ( final String attributeName , final Object value ) { return new StringBuilder ( ) . append ( "<cas:" . concat ( attributeName ) . concat ( ">" ) ) . append ( encodeAttributeValue ( value ) ) . append ( "</cas:" . concat ( attributeName ) . concat ( ">" ) ) . toString ( ) ; } | Build single attribute definition line . |
17,909 | @ View ( name = "by_username" , map = "function(doc) { if(doc.publicId && doc.username) {emit(doc.username, doc)}}" ) public YubiKeyAccount findByUsername ( final String uid ) { val view = createQuery ( "by_username" ) . key ( uid ) . limit ( 1 ) . includeDocs ( true ) ; return db . queryView ( view , CouchDbYubiKeyAccount . class ) . stream ( ) . findFirst ( ) . orElse ( null ) ; } | Find by username . |
17,910 | public static void rebindCasConfigurationProperties ( final ConfigurationPropertiesBindingPostProcessor binder , final ApplicationContext applicationContext ) { val map = applicationContext . getBeansOfType ( CasConfigurationProperties . class ) ; val name = map . keySet ( ) . iterator ( ) . next ( ) ; LOGGER . trace ( "Reloading CAS configuration via [{}]" , name ) ; val e = applicationContext . getBean ( name ) ; binder . postProcessBeforeInitialization ( e , name ) ; val bean = applicationContext . getAutowireCapableBeanFactory ( ) . initializeBean ( e , name ) ; applicationContext . getAutowireCapableBeanFactory ( ) . autowireBean ( bean ) ; LOGGER . debug ( "Reloaded CAS configuration [{}]" , name ) ; } | Rebind cas configuration properties . |
17,911 | public File getStandaloneProfileConfigurationDirectory ( ) { val file = environment . getProperty ( "cas.standalone.configurationDirectory" , File . class ) ; if ( file != null && file . exists ( ) ) { LOGGER . trace ( "Received standalone configuration directory [{}]" , file ) ; return file ; } return Arrays . stream ( DEFAULT_CAS_CONFIG_DIRECTORIES ) . filter ( File :: exists ) . findFirst ( ) . orElse ( null ) ; } | Gets standalone profile configuration directory . |
17,912 | protected Collection < SingleLogoutRequest > createLogoutRequests ( final String ticketId , final WebApplicationService selectedService , final RegisteredService registeredService , final Collection < SingleLogoutUrl > logoutUrls , final TicketGrantingTicket ticketGrantingTicket ) { return logoutUrls . stream ( ) . map ( url -> createLogoutRequest ( ticketId , selectedService , registeredService , url , ticketGrantingTicket ) ) . filter ( Objects :: nonNull ) . collect ( Collectors . toList ( ) ) ; } | Create logout requests collection . |
17,913 | protected SingleLogoutRequest createLogoutRequest ( final String ticketId , final WebApplicationService selectedService , final RegisteredService registeredService , final SingleLogoutUrl logoutUrl , final TicketGrantingTicket ticketGrantingTicket ) { val logoutRequest = DefaultSingleLogoutRequest . builder ( ) . ticketId ( ticketId ) . service ( selectedService ) . logoutUrl ( new URL ( logoutUrl . getUrl ( ) ) ) . logoutType ( logoutUrl . getLogoutType ( ) ) . registeredService ( registeredService ) . ticketGrantingTicket ( ticketGrantingTicket ) . properties ( logoutUrl . getProperties ( ) ) . build ( ) ; LOGGER . trace ( "Logout request [{}] created for [{}] and ticket id [{}]" , logoutRequest , selectedService , ticketId ) ; if ( logoutRequest . getLogoutType ( ) == RegisteredServiceLogoutType . BACK_CHANNEL ) { if ( performBackChannelLogout ( logoutRequest ) ) { logoutRequest . setStatus ( LogoutRequestStatus . SUCCESS ) ; } else { logoutRequest . setStatus ( LogoutRequestStatus . FAILURE ) ; LOGGER . warn ( "Logout message is not sent to [{}]; Continuing processing..." , selectedService ) ; } } else { LOGGER . trace ( "Logout operation is not yet attempted for [{}] given logout type is set to [{}]" , selectedService , logoutRequest . getLogoutType ( ) ) ; logoutRequest . setStatus ( LogoutRequestStatus . NOT_ATTEMPTED ) ; } return logoutRequest ; } | Create logout request logout request . |
17,914 | protected boolean sendSingleLogoutMessage ( final SingleLogoutRequest request , final SingleLogoutMessage logoutMessage ) { val logoutService = request . getService ( ) ; LOGGER . trace ( "Preparing logout request for [{}] to [{}]" , logoutService . getId ( ) , request . getLogoutUrl ( ) ) ; val msg = getLogoutHttpMessageToSend ( request , logoutMessage ) ; LOGGER . debug ( "Prepared logout message to send is [{}]. Sending..." , msg ) ; val result = sendMessageToEndpoint ( msg , request , logoutMessage ) ; logoutService . setLoggedOutAlready ( result ) ; return result ; } | Send single logout message . |
17,915 | protected boolean sendMessageToEndpoint ( final LogoutHttpMessage msg , final SingleLogoutRequest request , final SingleLogoutMessage logoutMessage ) { return this . httpClient . sendMessageToEndPoint ( msg ) ; } | Send message to endpoint . |
17,916 | protected LogoutHttpMessage getLogoutHttpMessageToSend ( final SingleLogoutRequest request , final SingleLogoutMessage logoutMessage ) { return new LogoutHttpMessage ( request . getLogoutUrl ( ) , logoutMessage . getPayload ( ) , this . asynchronous ) ; } | Gets logout http message to send . |
17,917 | public String handle ( final Exception e , final RequestContext requestContext ) { val messageContext = requestContext . getMessageContext ( ) ; if ( e instanceof AuthenticationException ) { return handleAuthenticationException ( ( AuthenticationException ) e , requestContext ) ; } if ( e instanceof AbstractTicketException ) { return handleAbstractTicketException ( ( AbstractTicketException ) e , requestContext ) ; } LOGGER . trace ( "Unable to translate errors of the authentication exception [{}]. Returning [{}]" , e , UNKNOWN ) ; val messageCode = this . messageBundlePrefix + UNKNOWN ; messageContext . addMessage ( new MessageBuilder ( ) . error ( ) . code ( messageCode ) . build ( ) ) ; return UNKNOWN ; } | Maps an authentication exception onto a state name . Also sets an ERROR severity message in the message context . |
17,918 | protected void checkSubjectRolesAndPermissions ( final Subject currentUser ) throws FailedLoginException { if ( this . requiredRoles != null ) { for ( val role : this . requiredRoles ) { if ( ! currentUser . hasRole ( role ) ) { throw new FailedLoginException ( "Required role " + role + " does not exist" ) ; } } } if ( this . requiredPermissions != null ) { for ( val perm : this . requiredPermissions ) { if ( ! currentUser . isPermitted ( perm ) ) { throw new FailedLoginException ( "Required permission " + perm + " cannot be located" ) ; } } } } | Check subject roles and permissions . |
17,919 | protected AuthenticationHandlerExecutionResult createAuthenticatedSubjectResult ( final Credential credential , final Subject currentUser ) { val username = currentUser . getPrincipal ( ) . toString ( ) ; return createHandlerResult ( credential , this . principalFactory . createPrincipal ( username ) ) ; } | Create authenticated subject result . |
17,920 | protected String extractPrincipalId ( final Credential credentials , final Optional < Principal > currentPrincipal ) { val wsFedCredentials = ( WsFederationCredential ) credentials ; val attributes = wsFedCredentials . getAttributes ( ) ; LOGGER . debug ( "Credential attributes provided are: [{}]" , attributes ) ; val idAttribute = this . configuration . getIdentityAttribute ( ) ; if ( attributes . containsKey ( idAttribute ) ) { LOGGER . debug ( "Extracting principal id from attribute [{}]" , this . configuration . getIdentityAttribute ( ) ) ; val idAttributeAsList = CollectionUtils . toCollection ( attributes . get ( this . configuration . getIdentityAttribute ( ) ) ) ; if ( idAttributeAsList . size ( ) > 1 ) { LOGGER . warn ( "Found multiple values for id attribute [{}]." , idAttribute ) ; } else { LOGGER . debug ( "Found principal id attribute as [{}]" , idAttributeAsList ) ; } val result = CollectionUtils . firstElement ( idAttributeAsList ) ; if ( result . isPresent ( ) ) { val principalId = result . get ( ) . toString ( ) ; LOGGER . debug ( "Principal Id extracted from credentials: [{}]" , principalId ) ; return principalId ; } } LOGGER . warn ( "Credential attributes do not include an attribute for [{}]. " + "This will prohibit CAS to construct a meaningful authenticated principal. " + "Examine the released claims and ensure [{}] is allowed" , idAttribute , idAttribute ) ; return null ; } | Extracts the principalId . |
17,921 | @ View ( name = "by_username" , map = "function(doc) { if(doc.username){ emit(doc.username, doc) } }" ) public CouchDbProfileDocument findByUsername ( final String username ) { return queryView ( "by_username" , username ) . stream ( ) . findFirst ( ) . orElse ( null ) ; } | Find profile by username . |
17,922 | @ View ( name = "by_linkedid" , map = "function(doc) { if(doc.linkedid){ emit(doc.linkedid, doc) } }" ) public CouchDbProfileDocument findByLinkedid ( final String linkedid ) { return queryView ( "by_linkedid" , linkedid ) . stream ( ) . findFirst ( ) . orElse ( null ) ; } | Find profile by linkedid . |
17,923 | public Collection < RegisteredService > load ( ) { LOGGER . trace ( "Loading services from [{}]" , serviceRegistry . getName ( ) ) ; this . services = this . serviceRegistry . load ( ) . stream ( ) . collect ( Collectors . toConcurrentMap ( r -> { LOGGER . debug ( "Adding registered service [{}]" , r . getServiceId ( ) ) ; return r . getId ( ) ; } , Function . identity ( ) , ( r , s ) -> s == null ? r : s ) ) ; loadInternal ( ) ; publishEvent ( new CasRegisteredServicesLoadedEvent ( this , getAllServices ( ) ) ) ; evaluateExpiredServiceDefinitions ( ) ; LOGGER . info ( "Loaded [{}] service(s) from [{}]." , this . services . size ( ) , this . serviceRegistry . getName ( ) ) ; return services . values ( ) ; } | Load services that are provided by the DAO . |
17,924 | @ View ( name = "by_recordKey" , map = "function(doc) { if (doc.principal && doc.deviceFingerprint && doc.recordDate) { emit(doc.recordKey, doc) } }" ) public CouchDbMultifactorAuthenticationTrustRecord findByRecordKey ( final String recordKey ) { return db . queryView ( createQuery ( "by_recordKey" ) . key ( recordKey ) . limit ( 1 ) , CouchDbMultifactorAuthenticationTrustRecord . class ) . stream ( ) . findFirst ( ) . orElse ( null ) ; } | Find by recordKey . |
17,925 | @ View ( name = "by_recordDate" , map = "function(doc) { if (doc.principal && doc.deviceFingerprint && doc.recordDate) { emit(doc.recordDate, doc) } }" ) public List < CouchDbMultifactorAuthenticationTrustRecord > findOnOrBeforeDate ( final LocalDateTime recordDate ) { return db . queryView ( createQuery ( "by_recordDate" ) . endKey ( recordDate ) , CouchDbMultifactorAuthenticationTrustRecord . class ) ; } | Find by recordDate on of before date . |
17,926 | public List < CouchDbMultifactorAuthenticationTrustRecord > findOnOrAfterDate ( final LocalDateTime onOrAfterDate ) { return db . queryView ( createQuery ( "by_recordDate" ) . startKey ( onOrAfterDate ) , CouchDbMultifactorAuthenticationTrustRecord . class ) ; } | Find record created on or after date . |
17,927 | @ View ( name = "by_principal" , map = "function(doc) { if (doc.principal && doc.deviceFingerprint && doc.recordDate) { emit(doc.principal, doc) } }" ) public List < CouchDbMultifactorAuthenticationTrustRecord > findByPrincipal ( final String principal ) { val view = createQuery ( "by_principal" ) . key ( principal ) ; return db . queryView ( view , CouchDbMultifactorAuthenticationTrustRecord . class ) ; } | Find by principal name . |
17,928 | @ View ( name = "by_principal_date" , map = "function(doc) { if (doc.recordKey && doc.principal && doc.deviceFingerprint && doc.recordDate) { emit([doc.principal, doc.recordDate], doc) } }" ) public List < CouchDbMultifactorAuthenticationTrustRecord > findByPrincipalAfterDate ( final String principal , final LocalDateTime onOrAfterDate ) { val view = createQuery ( "by_principal_date" ) . startKey ( ComplexKey . of ( principal , onOrAfterDate ) ) . endKey ( ComplexKey . of ( principal , "999999" ) ) ; return db . queryView ( view , CouchDbMultifactorAuthenticationTrustRecord . class ) ; } | Find by principal on or after date . |
17,929 | protected Map < String , List < Object > > convertAttributesToPrincipalAttributesAndCache ( final Principal principal , final Map < String , List < Object > > sourceAttributes , final RegisteredService registeredService ) { val finalAttributes = convertPersonAttributesToPrincipalAttributes ( sourceAttributes ) ; addPrincipalAttributes ( principal . getId ( ) , finalAttributes , registeredService ) ; return finalAttributes ; } | Convert attributes to principal attributes and cache . |
17,930 | protected static Map < String , List < Object > > convertPersonAttributesToPrincipalAttributes ( final Map < String , List < Object > > attributes ) { return attributes . entrySet ( ) . stream ( ) . collect ( Collectors . toMap ( Map . Entry :: getKey , Map . Entry :: getValue ) ) ; } | Convert person attributes to principal attributes . |
17,931 | protected Map < String , List < Object > > getPrincipalAttributes ( final Principal principal ) { if ( ignoreResolvedAttributes ) { return new HashMap < > ( 0 ) ; } return convertPrincipalAttributesToPersonAttributes ( principal . getAttributes ( ) ) ; } | Gets principal attributes . |
17,932 | protected RegisteredService getRegisteredServiceFromFile ( final File file ) { val fileName = file . getName ( ) ; if ( fileName . startsWith ( "." ) ) { LOGGER . trace ( "[{}] starts with ., ignoring" , fileName ) ; return null ; } if ( Arrays . stream ( getExtensions ( ) ) . noneMatch ( fileName :: endsWith ) ) { LOGGER . trace ( "[{}] doesn't end with valid extension, ignoring" , fileName ) ; return null ; } val matcher = this . serviceFileNamePattern . matcher ( fileName ) ; if ( matcher . find ( ) ) { val serviceId = matcher . group ( 2 ) ; if ( NumberUtils . isCreatable ( serviceId ) ) { val id = Long . parseLong ( serviceId ) ; return findServiceById ( id ) ; } val serviceName = matcher . group ( 1 ) ; return findServiceByExactServiceName ( serviceName ) ; } LOGGER . warn ( "Provided file [{}} does not match the recommended service definition file pattern [{}]" , file . getName ( ) , this . serviceFileNamePattern . pattern ( ) ) ; return null ; } | Gets registered service from file . |
17,933 | protected void decideIfCredentialPasswordShouldBeReleasedAsAttribute ( final Map < String , List < Object > > attributes , final Authentication authentication , final RegisteredService service ) { val policy = service . getAttributeReleasePolicy ( ) ; val isAuthorized = policy != null && policy . isAuthorizedToReleaseCredentialPassword ( ) ; val element = CollectionUtils . firstElement ( authentication . getAttributes ( ) . get ( CasViewConstants . MODEL_ATTRIBUTE_NAME_PRINCIPAL_CREDENTIAL ) ) ; val credential = element . map ( Object :: toString ) . orElse ( null ) ; decideAttributeReleaseBasedOnServiceAttributePolicy ( attributes , credential , CasViewConstants . MODEL_ATTRIBUTE_NAME_PRINCIPAL_CREDENTIAL , service , isAuthorized ) ; } | Decide if credential password should be released as attribute . The credential must have been cached as an authentication attribute and the attribute release policy must be allowed to release the attribute . |
17,934 | protected void decideIfProxyGrantingTicketShouldBeReleasedAsAttribute ( final Map < String , List < Object > > attributes , final Map < String , Object > model , final RegisteredService service ) { val policy = service . getAttributeReleasePolicy ( ) ; val isAuthorized = policy != null && policy . isAuthorizedToReleaseProxyGrantingTicket ( ) ; val pgtIou = ( String ) model . get ( CasViewConstants . MODEL_ATTRIBUTE_NAME_PROXY_GRANTING_TICKET_IOU ) ; decideAttributeReleaseBasedOnServiceAttributePolicy ( attributes , pgtIou , CasViewConstants . MODEL_ATTRIBUTE_NAME_PROXY_GRANTING_TICKET_IOU , service , isAuthorized ) ; val pgtId = ( String ) model . get ( CasViewConstants . MODEL_ATTRIBUTE_NAME_PROXY_GRANTING_TICKET ) ; decideAttributeReleaseBasedOnServiceAttributePolicy ( attributes , pgtId , CasViewConstants . MODEL_ATTRIBUTE_NAME_PROXY_GRANTING_TICKET , service , isAuthorized ) ; } | Decide if PGT should be released as attribute . The PGT must have been cached as an authentication attribute and the attribute release policy must be allowed to release the attribute . |
17,935 | protected void decideAttributeReleaseBasedOnServiceAttributePolicy ( final Map < String , List < Object > > attributes , final String attributeValue , final String attributeName , final RegisteredService service , final boolean doesAttributePolicyAllow ) { if ( StringUtils . isNotBlank ( attributeValue ) ) { LOGGER . debug ( "Obtained [{}] as an authentication attribute" , attributeName ) ; if ( doesAttributePolicyAllow ) { LOGGER . debug ( "Obtained [{}] is passed to the CAS validation payload" , attributeName ) ; attributes . put ( attributeName , CollectionUtils . wrap ( attributeValue ) ) ; } else { LOGGER . debug ( "Attribute release policy for [{}] does not authorize the release of [{}]" , service . getServiceId ( ) , attributeName ) ; attributes . remove ( attributeName ) ; } } else { LOGGER . trace ( "[{}] is not available and will not be released to the validation response." , attributeName ) ; } } | Decide attribute release based on service attribute policy . |
17,936 | protected String determinePrincipalId ( final RequestContext requestContext , final Credential credential ) { if ( StringUtils . isBlank ( properties . getJdbc ( ) . getPrincipalIdAttribute ( ) ) ) { return credential . getId ( ) ; } val principal = WebUtils . getAuthentication ( requestContext ) . getPrincipal ( ) ; val pIdAttribName = properties . getJdbc ( ) . getPrincipalIdAttribute ( ) ; if ( ! principal . getAttributes ( ) . containsKey ( pIdAttribName ) ) { throw new IllegalStateException ( "Principal attribute [" + pIdAttribName + "] cannot be found" ) ; } val pIdAttributeValue = principal . getAttributes ( ) . get ( pIdAttribName ) ; val pIdAttributeValues = CollectionUtils . toCollection ( pIdAttributeValue ) ; var principalId = StringUtils . EMPTY ; if ( ! pIdAttributeValues . isEmpty ( ) ) { principalId = pIdAttributeValues . iterator ( ) . next ( ) . toString ( ) . trim ( ) ; } if ( pIdAttributeValues . size ( ) > 1 ) { LOGGER . warn ( "Principal attribute [{}] was found, but its value [{}] is multi-valued. " + "Proceeding with the first element [{}]" , pIdAttribName , pIdAttributeValue , principalId ) ; } if ( principalId . isEmpty ( ) ) { throw new IllegalStateException ( "Principal attribute [" + pIdAttribName + "] was found, but it is either empty" + " or multi-valued with an empty element" ) ; } return principalId ; } | Extracts principal ID from a principal attribute or the provided credentials . |
17,937 | public static ClientConfiguration buildClientConfiguration ( final BaseAmazonWebServicesProperties props ) { val cfg = new ClientConfiguration ( ) ; cfg . setConnectionTimeout ( props . getConnectionTimeout ( ) ) ; cfg . setMaxConnections ( props . getMaxConnections ( ) ) ; cfg . setRequestTimeout ( props . getRequestTimeout ( ) ) ; cfg . setSocketTimeout ( props . getSocketTimeout ( ) ) ; cfg . setUseGzip ( props . isUseGzip ( ) ) ; cfg . setUseReaper ( props . isUseReaper ( ) ) ; cfg . setUseThrottleRetries ( props . isUseThrottleRetries ( ) ) ; cfg . setUseTcpKeepAlive ( props . isUseTcpKeepAlive ( ) ) ; cfg . setProtocol ( Protocol . valueOf ( props . getProtocol ( ) . toUpperCase ( ) ) ) ; cfg . setClientExecutionTimeout ( props . getClientExecutionTimeout ( ) ) ; if ( props . getMaxErrorRetry ( ) > 0 ) { cfg . setMaxErrorRetry ( props . getMaxErrorRetry ( ) ) ; } cfg . setProxyHost ( props . getProxyHost ( ) ) ; cfg . setProxyPassword ( props . getProxyPassword ( ) ) ; if ( props . getProxyPort ( ) > 0 ) { cfg . setProxyPort ( props . getProxyPort ( ) ) ; } cfg . setProxyUsername ( props . getProxyUsername ( ) ) ; cfg . setCacheResponseMetadata ( props . isCacheResponseMetadata ( ) ) ; if ( StringUtils . isNotBlank ( props . getLocalAddress ( ) ) ) { LOGGER . trace ( "Creating DynamoDb client local address [{}]" , props . getLocalAddress ( ) ) ; cfg . setLocalAddress ( InetAddress . getByName ( props . getLocalAddress ( ) ) ) ; } return cfg ; } | Build client configuration . |
17,938 | private List filterAttributes ( final List < Object > valuesToFilter , final String attributeName ) { return valuesToFilter . stream ( ) . filter ( this :: patternMatchesAttributeValue ) . peek ( attributeValue -> logReleasedAttributeEntry ( attributeName , attributeValue ) ) . collect ( Collectors . toList ( ) ) ; } | Filter array attributes . |
17,939 | private boolean patternMatchesAttributeValue ( final Object value ) { val matcher = value . toString ( ) ; LOGGER . trace ( "Compiling a pattern matcher for [{}]" , matcher ) ; return this . compiledPattern . matcher ( matcher ) . matches ( ) ; } | Determine whether pattern matches attribute value . |
17,940 | private void logReleasedAttributeEntry ( final String attributeName , final Object attributeValue ) { LOGGER . debug ( "The attribute value [{}] for attribute name [{}] matches the pattern [{}]. Releasing attribute..." , attributeValue , attributeName , this . compiledPattern . pattern ( ) ) ; } | Logs the released attribute entry . |
17,941 | protected InputStream getResourceInputStream ( final Resource resource , final String entityId ) throws IOException { LOGGER . debug ( "Locating metadata resource from input stream." ) ; if ( ! resource . exists ( ) || ! resource . isReadable ( ) ) { throw new FileNotFoundException ( "Resource does not exist or is unreadable" ) ; } return resource . getInputStream ( ) ; } | Retrieve the remote source s input stream to parse data . |
17,942 | public void buildMetadataResolverAggregate ( final String entityId ) { LOGGER . trace ( "Building metadata resolver aggregate" ) ; this . metadataResolver = new ChainingMetadataResolver ( ) ; val resolvers = new ArrayList < MetadataResolver > ( ) ; val entries = this . metadataResources . entrySet ( ) ; entries . forEach ( entry -> { val resource = entry . getKey ( ) ; LOGGER . debug ( "Loading [{}]" , resource . getFilename ( ) ) ; resolvers . addAll ( loadMetadataFromResource ( entry . getValue ( ) , resource , entityId ) ) ; } ) ; this . metadataResolver . setId ( ChainingMetadataResolver . class . getCanonicalName ( ) ) ; this . metadataResolver . setResolvers ( resolvers ) ; LOGGER . debug ( "Collected metadata from [{}] resolvers(s). Initializing aggregate resolver..." , resolvers . size ( ) ) ; this . metadataResolver . initialize ( ) ; LOGGER . info ( "Metadata aggregate initialized successfully." ) ; } | Build metadata resolver aggregate . Loops through metadata resources and attempts to resolve the metadata . |
17,943 | private List < MetadataResolver > loadMetadataFromResource ( final MetadataFilter metadataFilter , final Resource resource , final String entityId ) { LOGGER . debug ( "Evaluating metadata resource [{}]" , resource . getFilename ( ) ) ; try ( val in = getResourceInputStream ( resource , entityId ) ) { if ( in . available ( ) > 0 && in . markSupported ( ) ) { LOGGER . debug ( "Parsing [{}]" , resource . getFilename ( ) ) ; val document = this . configBean . getParserPool ( ) . parse ( in ) ; return buildSingleMetadataResolver ( metadataFilter , resource , document ) ; } LOGGER . warn ( "Input stream from resource [{}] appears empty. Moving on..." , resource . getFilename ( ) ) ; } catch ( final Exception e ) { LOGGER . warn ( "Could not retrieve input stream from resource. Moving on..." , e ) ; } return new ArrayList < > ( 0 ) ; } | Load metadata from resource . |
17,944 | private List < MetadataResolver > buildSingleMetadataResolver ( final MetadataFilter metadataFilterChain , final Resource resource , final Document document ) { try { val metadataRoot = document . getDocumentElement ( ) ; val metadataProvider = new DOMMetadataResolver ( metadataRoot ) ; metadataProvider . setParserPool ( this . configBean . getParserPool ( ) ) ; metadataProvider . setFailFastInitialization ( true ) ; metadataProvider . setRequireValidMetadata ( this . requireValidMetadata ) ; metadataProvider . setId ( metadataProvider . getClass ( ) . getCanonicalName ( ) ) ; if ( metadataFilterChain != null ) { metadataProvider . setMetadataFilter ( metadataFilterChain ) ; } LOGGER . debug ( "Initializing metadata resolver for [{}]" , resource ) ; metadataProvider . initialize ( ) ; val resolvers = new ArrayList < MetadataResolver > ( ) ; resolvers . add ( metadataProvider ) ; return resolvers ; } catch ( final Exception ex ) { LOGGER . warn ( "Could not initialize metadata resolver. Resource will be ignored" , ex ) ; } return new ArrayList < > ( 0 ) ; } | Build single metadata resolver . |
17,945 | public static AuthenticationBuilder newInstance ( final Authentication source ) { val builder = new DefaultAuthenticationBuilder ( source . getPrincipal ( ) ) ; builder . setAuthenticationDate ( source . getAuthenticationDate ( ) ) ; builder . setCredentials ( source . getCredentials ( ) ) ; builder . setSuccesses ( source . getSuccesses ( ) ) ; builder . setFailures ( source . getFailures ( ) ) ; builder . setAttributes ( source . getAttributes ( ) ) ; builder . setWarnings ( source . getWarnings ( ) ) ; return builder ; } | Creates a new builder initialized with data from the given authentication source . |
17,946 | public AuthenticationBuilder setCredentials ( final List < CredentialMetaData > credentials ) { this . credentials . clear ( ) ; this . credentials . addAll ( credentials ) ; return this ; } | Sets the list of metadata about credentials presented for authentication . |
17,947 | protected boolean doesEndingTimeAllowServiceAccess ( ) { if ( this . endingDateTime != null ) { val et = DateTimeUtils . zonedDateTimeOf ( this . endingDateTime ) ; if ( et != null ) { val now = ZonedDateTime . now ( ZoneOffset . UTC ) ; if ( now . isAfter ( et ) ) { LOGGER . warn ( "Service access not allowed because it ended at [{}]. Now is [{}]" , this . endingDateTime , now ) ; return false ; } } else { val etLocal = DateTimeUtils . localDateTimeOf ( this . endingDateTime ) ; if ( etLocal != null ) { val now = LocalDateTime . now ( ZoneOffset . UTC ) ; if ( now . isAfter ( etLocal ) ) { LOGGER . warn ( "Service access not allowed because it ended at [{}]. Now is [{}]" , this . endingDateTime , now ) ; return false ; } } } } return true ; } | Does ending time allow service access boolean . |
17,948 | protected boolean doesStartingTimeAllowServiceAccess ( ) { if ( this . startingDateTime != null ) { val st = DateTimeUtils . zonedDateTimeOf ( this . startingDateTime ) ; if ( st != null ) { val now = ZonedDateTime . now ( ZoneOffset . UTC ) ; if ( now . isBefore ( st ) ) { LOGGER . warn ( "Service access not allowed because it starts at [{}]. Zoned now is [{}]" , this . startingDateTime , now ) ; return false ; } } else { val stLocal = DateTimeUtils . localDateTimeOf ( this . startingDateTime ) ; if ( stLocal != null ) { val now = LocalDateTime . now ( ZoneOffset . UTC ) ; if ( now . isBefore ( stLocal ) ) { LOGGER . warn ( "Service access not allowed because it starts at [{}]. Local now is [{}]" , this . startingDateTime , now ) ; return false ; } } } } return true ; } | Does starting time allow service access boolean . |
17,949 | protected Optional < ExpirationPolicy > getExpirationPolicyFor ( final TicketState ticketState ) { val name = getExpirationPolicyNameFor ( ticketState ) ; LOGGER . trace ( "Received expiration policy name [{}] to activate" , name ) ; if ( StringUtils . isNotBlank ( name ) && policies . containsKey ( name ) ) { val policy = policies . get ( name ) ; LOGGER . trace ( "Located expiration policy [{}] by name [{}]" , policy , name ) ; return Optional . of ( policy ) ; } LOGGER . warn ( "No expiration policy could be found by the name [{}] for ticket state [{}]" , name , ticketState ) ; return Optional . empty ( ) ; } | Gets expiration policy by its name . |
17,950 | public static SPSSODescriptor getSPSsoDescriptor ( final EntityDescriptor entityDescriptor ) { LOGGER . trace ( "Locating SP SSO descriptor for SAML2 protocol..." ) ; var spssoDescriptor = entityDescriptor . getSPSSODescriptor ( SAMLConstants . SAML20P_NS ) ; if ( spssoDescriptor == null ) { LOGGER . trace ( "Locating SP SSO descriptor for SAML11 protocol..." ) ; spssoDescriptor = entityDescriptor . getSPSSODescriptor ( SAMLConstants . SAML11P_NS ) ; } if ( spssoDescriptor == null ) { LOGGER . trace ( "Locating SP SSO descriptor for SAML1 protocol..." ) ; spssoDescriptor = entityDescriptor . getSPSSODescriptor ( SAMLConstants . SAML10P_NS ) ; } LOGGER . trace ( "SP SSO descriptor resolved to be [{}]" , spssoDescriptor ) ; return spssoDescriptor ; } | Gets SP SSO descriptor . |
17,951 | public static SamlMetadataUIInfo locateMetadataUserInterfaceForEntityId ( final MetadataResolverAdapter metadataAdapter , final String entityId , final RegisteredService registeredService , final HttpServletRequest requestContext ) { val entityDescriptor = metadataAdapter . getEntityDescriptorForEntityId ( entityId ) ; return locateMetadataUserInterfaceForEntityId ( entityDescriptor , entityId , registeredService , requestContext ) ; } | Locate MDUI for entity id simple metadata ui info . |
17,952 | public static SamlMetadataUIInfo locateMetadataUserInterfaceForEntityId ( final EntityDescriptor entityDescriptor , final String entityId , final RegisteredService registeredService , final HttpServletRequest requestContext ) { val mdui = new SamlMetadataUIInfo ( registeredService , requestContext . getLocale ( ) . getLanguage ( ) ) ; if ( entityDescriptor == null ) { LOGGER . trace ( "Entity descriptor not found for [{}]" , entityId ) ; return mdui ; } val spssoDescriptor = getSPSsoDescriptor ( entityDescriptor ) ; if ( spssoDescriptor == null ) { LOGGER . trace ( "SP SSO descriptor not found for [{}]" , entityId ) ; return mdui ; } val extensions = spssoDescriptor . getExtensions ( ) ; if ( extensions == null ) { LOGGER . trace ( "No extensions in the SP SSO descriptor are found for [{}]" , UIInfo . DEFAULT_ELEMENT_NAME . getNamespaceURI ( ) ) ; return mdui ; } val spExtensions = extensions . getUnknownXMLObjects ( UIInfo . DEFAULT_ELEMENT_NAME ) ; if ( spExtensions . isEmpty ( ) ) { LOGGER . trace ( "No extensions in the SP SSO descriptor are located for [{}]" , UIInfo . DEFAULT_ELEMENT_NAME . getNamespaceURI ( ) ) ; return mdui ; } spExtensions . stream ( ) . filter ( UIInfo . class :: isInstance ) . forEach ( obj -> { val uiInfo = ( UIInfo ) obj ; LOGGER . trace ( "Found MDUI info for [{}]" , entityId ) ; mdui . setUiInfo ( uiInfo ) ; } ) ; return mdui ; } | Locate mdui for entity id simple metadata ui info . |
17,953 | @ View ( name = "by_serviceId" , map = "function(doc) { if (doc.service) { emit(doc.service.serviceId, doc._id) }}" ) public RegisteredServiceDocument findByServiceId ( final String serviceId ) { return queryView ( "by_serviceId" , serviceId ) . stream ( ) . findFirst ( ) . orElse ( null ) ; } | Implements search by serviceId . |
17,954 | @ View ( name = "by_serviceName" , map = "function(doc) { if (doc.service) { emit(doc.service.name, doc._id) }}" ) public RegisteredServiceDocument findByServiceName ( final String serviceName ) { try { return queryView ( "by_serviceName" , serviceName ) . stream ( ) . findFirst ( ) . orElse ( null ) ; } catch ( final DocumentNotFoundException e ) { LOGGER . debug ( "Service [{}] not found. [{}]" , serviceName , e . getMessage ( ) ) ; return null ; } } | Implements search by service name . |
17,955 | public RegisteredServiceDocument get ( final long id ) { try { return this . get ( String . valueOf ( id ) ) ; } catch ( final DocumentNotFoundException e ) { LOGGER . debug ( "Service [{}] not found. [{}]" , id , e . getMessage ( ) ) ; return null ; } } | Overload wrapper for long type . Get service by ID . |
17,956 | @ View ( name = "size" , map = "function(doc) { if (doc.service) { emit(doc, doc._id) }}" , reduce = "_count" ) public int size ( ) { val r = db . queryView ( createQuery ( "size" ) ) ; LOGGER . trace ( "r.isEmpty [{}]" , r . isEmpty ( ) ) ; LOGGER . trace ( "r.getRows [{}]" , r . getRows ( ) ) ; if ( r . isEmpty ( ) ) { return 0 ; } return r . getRows ( ) . get ( 0 ) . getValueAsInt ( ) ; } | Size of the service database . |
17,957 | private static String getRequestBody ( final HttpServletRequest request ) { val body = readRequestBodyIfAny ( request ) ; if ( ! StringUtils . hasText ( body ) ) { LOGGER . trace ( "Looking at the request attribute [{}] to locate SAML request body" , SamlProtocolConstants . PARAMETER_SAML_REQUEST ) ; return ( String ) request . getAttribute ( SamlProtocolConstants . PARAMETER_SAML_REQUEST ) ; } return body ; } | Gets the request body from the request . |
17,958 | public static < T > T registerBeanIntoApplicationContext ( final ConfigurableApplicationContext applicationContext , final Class < T > beanClazz , final String beanId ) { val beanFactory = applicationContext . getBeanFactory ( ) ; val provider = beanFactory . createBean ( beanClazz ) ; beanFactory . initializeBean ( provider , beanId ) ; beanFactory . autowireBean ( provider ) ; beanFactory . registerSingleton ( beanId , provider ) ; return provider ; } | Register bean into application context . |
17,959 | public static < T > T registerBeanIntoApplicationContext ( final ConfigurableApplicationContext applicationContext , final T beanInstance , final String beanId ) { val beanFactory = applicationContext . getBeanFactory ( ) ; if ( beanFactory . containsBean ( beanId ) ) { return ( T ) applicationContext . getBean ( beanId , beanInstance . getClass ( ) ) ; } beanFactory . initializeBean ( beanInstance , beanId ) ; beanFactory . autowireBean ( beanInstance ) ; beanFactory . registerSingleton ( beanId , beanInstance ) ; return beanInstance ; } | Register bean into application context t . |
17,960 | public static Optional < CasConfigurationProperties > getCasConfigurationProperties ( ) { if ( CONTEXT != null ) { return Optional . of ( CONTEXT . getBean ( CasConfigurationProperties . class ) ) ; } return Optional . empty ( ) ; } | Gets cas properties . |
17,961 | protected Map < String , List < Object > > getCachedPrincipalAttributes ( final Principal principal , final RegisteredService registeredService ) { try { val cache = getCacheInstanceFromApplicationContext ( ) ; return cache . getCachedAttributesFor ( registeredService , this , principal ) ; } catch ( final Exception e ) { LOGGER . error ( e . getMessage ( ) , e ) ; } return new HashMap < > ( 0 ) ; } | Gets cached principal attributes . |
17,962 | public PrincipalAttributesRepositoryCache getCacheInstanceFromApplicationContext ( ) { val ctx = ApplicationContextProvider . getApplicationContext ( ) ; return ctx . getBean ( "principalAttributesRepositoryCache" , PrincipalAttributesRepositoryCache . class ) ; } | Gets cache instance from application context . |
17,963 | protected void createGoogleAppsPrivateKey ( ) throws Exception { if ( ! isValidConfiguration ( ) ) { LOGGER . debug ( "Google Apps private key bean will not be created, because it's not configured" ) ; return ; } val bean = new PrivateKeyFactoryBean ( ) ; if ( this . privateKeyLocation . startsWith ( ResourceUtils . CLASSPATH_URL_PREFIX ) ) { bean . setLocation ( new ClassPathResource ( StringUtils . removeStart ( this . privateKeyLocation , ResourceUtils . CLASSPATH_URL_PREFIX ) ) ) ; } else if ( this . privateKeyLocation . startsWith ( ResourceUtils . FILE_URL_PREFIX ) ) { bean . setLocation ( new FileSystemResource ( StringUtils . removeStart ( this . privateKeyLocation , ResourceUtils . FILE_URL_PREFIX ) ) ) ; } else { bean . setLocation ( new FileSystemResource ( this . privateKeyLocation ) ) ; } bean . setAlgorithm ( this . keyAlgorithm ) ; LOGGER . debug ( "Loading Google Apps private key from [{}] with key algorithm [{}]" , bean . getLocation ( ) , bean . getAlgorithm ( ) ) ; bean . afterPropertiesSet ( ) ; LOGGER . debug ( "Creating Google Apps private key instance via [{}]" , this . privateKeyLocation ) ; this . privateKey = bean . getObject ( ) ; } | Create the private key . |
17,964 | protected void createGoogleAppsPublicKey ( ) throws Exception { if ( ! isValidConfiguration ( ) ) { LOGGER . debug ( "Google Apps public key bean will not be created, because it's not configured" ) ; return ; } val bean = new PublicKeyFactoryBean ( ) ; if ( this . publicKeyLocation . startsWith ( ResourceUtils . CLASSPATH_URL_PREFIX ) ) { bean . setResource ( new ClassPathResource ( StringUtils . removeStart ( this . publicKeyLocation , ResourceUtils . CLASSPATH_URL_PREFIX ) ) ) ; } else if ( this . publicKeyLocation . startsWith ( ResourceUtils . FILE_URL_PREFIX ) ) { bean . setResource ( new FileSystemResource ( StringUtils . removeStart ( this . publicKeyLocation , ResourceUtils . FILE_URL_PREFIX ) ) ) ; } else { bean . setResource ( new FileSystemResource ( this . publicKeyLocation ) ) ; } bean . setAlgorithm ( this . keyAlgorithm ) ; LOGGER . debug ( "Loading Google Apps public key from [{}] with key algorithm [{}]" , bean . getResource ( ) , bean . getAlgorithm ( ) ) ; bean . afterPropertiesSet ( ) ; LOGGER . debug ( "Creating Google Apps public key instance via [{}]" , this . publicKeyLocation ) ; this . publicKey = bean . getObject ( ) ; } | Create the public key . |
17,965 | protected ActionState createTerminateSessionActionState ( final Flow flow ) { val actionState = createActionState ( flow , CasWebflowConstants . STATE_ID_TERMINATE_SESSION , CasWebflowConstants . ACTION_ID_TERMINATE_SESSION ) ; createTransitionForState ( actionState , CasWebflowConstants . TRANSITION_ID_WARN , CasWebflowConstants . STATE_ID_CONFIRM_LOGOUT_VIEW ) ; createStateDefaultTransition ( actionState , CasWebflowConstants . STATE_ID_DO_LOGOUT ) ; return actionState ; } | Create terminate session action state . |
17,966 | protected void createLogoutViewState ( final Flow flow ) { val logoutView = createEndState ( flow , CasWebflowConstants . STATE_ID_LOGOUT_VIEW , "casLogoutView" ) ; logoutView . getEntryActionList ( ) . add ( createEvaluateAction ( CasWebflowConstants . ACTION_ID_LOGOUT_VIEW_SETUP ) ) ; } | Create logout view state . |
17,967 | protected void createFrontLogoutActionState ( final Flow flow ) { val actionState = createActionState ( flow , CasWebflowConstants . STATE_ID_FRONT_LOGOUT , createEvaluateAction ( "frontChannelLogoutAction" ) ) ; createTransitionForState ( actionState , CasWebflowConstants . TRANSITION_ID_FINISH , CasWebflowConstants . STATE_ID_FINISH_LOGOUT ) ; createTransitionForState ( actionState , CasWebflowConstants . TRANSITION_ID_PROPAGATE , CasWebflowConstants . STATE_ID_PROPAGATE_LOGOUT_REQUESTS ) ; } | Create front logout action state . |
17,968 | private void createDoLogoutActionState ( final Flow flow ) { val actionState = createActionState ( flow , CasWebflowConstants . STATE_ID_DO_LOGOUT , createEvaluateAction ( "logoutAction" ) ) ; createTransitionForState ( actionState , CasWebflowConstants . TRANSITION_ID_FINISH , CasWebflowConstants . STATE_ID_FINISH_LOGOUT ) ; createTransitionForState ( actionState , "front" , CasWebflowConstants . STATE_ID_FRONT_LOGOUT ) ; } | Create do logout action state . |
17,969 | protected void createLogoutConfirmationView ( final Flow flow ) { val view = createViewState ( flow , CasWebflowConstants . STATE_ID_CONFIRM_LOGOUT_VIEW , "casConfirmLogoutView" ) ; createTransitionForState ( view , CasWebflowConstants . TRANSITION_ID_SUCCESS , CasWebflowConstants . STATE_ID_TERMINATE_SESSION ) ; } | Create logout confirmation view . |
17,970 | public CouchDbSamlMetadataDocument merge ( final SamlMetadataDocument document ) { setId ( document . getId ( ) ) ; setName ( document . getName ( ) ) ; setValue ( document . getValue ( ) ) ; setSignature ( document . getSignature ( ) ) ; return this ; } | Merge other into this . |
17,971 | @ PostMapping ( value = "/v1/tickets/{tgtId:.+}" , consumes = MediaType . APPLICATION_FORM_URLENCODED_VALUE ) public ResponseEntity < String > createServiceTicket ( final HttpServletRequest httpServletRequest , @ RequestBody ( required = false ) final MultiValueMap < String , String > requestBody , @ PathVariable ( "tgtId" ) final String tgtId ) { try { val authn = this . ticketRegistrySupport . getAuthenticationFrom ( tgtId ) ; AuthenticationCredentialsThreadLocalBinder . bindCurrent ( authn ) ; if ( authn == null ) { throw new InvalidTicketException ( tgtId ) ; } val service = this . argumentExtractor . extractService ( httpServletRequest ) ; if ( service == null ) { throw new IllegalArgumentException ( "Target service/application is unspecified or unrecognized in the request" ) ; } if ( BooleanUtils . toBoolean ( httpServletRequest . getParameter ( CasProtocolConstants . PARAMETER_RENEW ) ) ) { val credential = this . credentialFactory . fromRequest ( httpServletRequest , requestBody ) ; if ( credential == null || credential . isEmpty ( ) ) { throw new BadRestRequestException ( "No credentials are provided or extracted to authenticate the REST request" ) ; } val authenticationResult = authenticationSystemSupport . handleAndFinalizeSingleAuthenticationTransaction ( service , credential ) ; return this . serviceTicketResourceEntityResponseFactory . build ( tgtId , service , authenticationResult ) ; } else { val builder = new DefaultAuthenticationResultBuilder ( ) ; val authenticationResult = builder . collect ( authn ) . build ( this . authenticationSystemSupport . getPrincipalElectionStrategy ( ) , service ) ; return this . serviceTicketResourceEntityResponseFactory . build ( tgtId , service , authenticationResult ) ; } } catch ( final InvalidTicketException e ) { return new ResponseEntity < > ( tgtId + " could not be found or is considered invalid" , HttpStatus . NOT_FOUND ) ; } catch ( final AuthenticationException e ) { return RestResourceUtils . createResponseEntityForAuthnFailure ( e , httpServletRequest , applicationContext ) ; } catch ( final BadRestRequestException e ) { LOGGER . error ( e . getMessage ( ) , e ) ; return new ResponseEntity < > ( e . getMessage ( ) , HttpStatus . BAD_REQUEST ) ; } catch ( final Exception e ) { LOGGER . error ( e . getMessage ( ) , e ) ; return new ResponseEntity < > ( e . getMessage ( ) , HttpStatus . INTERNAL_SERVER_ERROR ) ; } finally { AuthenticationCredentialsThreadLocalBinder . clear ( ) ; } } | Create new service ticket . |
17,972 | public static X509Certificate readCertificate ( final Resource resource ) { try ( val in = resource . getInputStream ( ) ) { return CertUtil . readCertificate ( in ) ; } catch ( final Exception e ) { throw new IllegalArgumentException ( "Error reading certificate " + resource , e ) ; } } | Read certificate x 509 certificate . |
17,973 | public static StringWriter transformSamlObject ( final OpenSamlConfigBean configBean , final XMLObject samlObject ) throws SamlException { return transformSamlObject ( configBean , samlObject , false ) ; } | Transform saml object into string without indenting the final string . |
17,974 | public static StringWriter transformSamlObject ( final OpenSamlConfigBean configBean , final XMLObject samlObject , final boolean indent ) throws SamlException { val writer = new StringWriter ( ) ; try { val marshaller = configBean . getMarshallerFactory ( ) . getMarshaller ( samlObject . getElementQName ( ) ) ; if ( marshaller != null ) { val element = marshaller . marshall ( samlObject ) ; val domSource = new DOMSource ( element ) ; val result = new StreamResult ( writer ) ; val tf = TransformerFactory . newInstance ( ) ; tf . setFeature ( XMLConstants . FEATURE_SECURE_PROCESSING , true ) ; val transformer = tf . newTransformer ( ) ; if ( indent ) { transformer . setOutputProperty ( OutputKeys . INDENT , "yes" ) ; transformer . setOutputProperty ( "{http://xml.apache.org/xslt}indent-amount" , "4" ) ; } transformer . transform ( domSource , result ) ; } } catch ( final Exception e ) { throw new SamlException ( e . getMessage ( ) , e ) ; } return writer ; } | Transform saml object to String . |
17,975 | public static BasicCredential buildCredentialForMetadataSignatureValidation ( final Resource resource ) throws Exception { try { val x509FactoryBean = new BasicX509CredentialFactoryBean ( ) ; x509FactoryBean . setCertificateResource ( resource ) ; x509FactoryBean . afterPropertiesSet ( ) ; return x509FactoryBean . getObject ( ) ; } catch ( final Exception e ) { LOGGER . trace ( e . getMessage ( ) , e ) ; LOGGER . debug ( "Credential cannot be extracted from [{}] via X.509. Treating it as a public key to locate credential..." , resource ) ; val credentialFactoryBean = new BasicResourceCredentialFactoryBean ( ) ; credentialFactoryBean . setPublicKeyInfo ( resource ) ; credentialFactoryBean . afterPropertiesSet ( ) ; return credentialFactoryBean . getObject ( ) ; } } | Build credential for metadata signature validation basic credential . |
17,976 | public static String logSamlObject ( final OpenSamlConfigBean configBean , final XMLObject samlObject ) throws SamlException { val repeat = "*" . repeat ( SAML_OBJECT_LOG_ASTERIXLINE_LENGTH ) ; LOGGER . debug ( repeat ) ; try ( val writer = transformSamlObject ( configBean , samlObject , true ) ) { LOGGER . debug ( "Logging [{}]\n\n[{}]\n\n" , samlObject . getClass ( ) . getName ( ) , writer ) ; LOGGER . debug ( repeat ) ; return writer . toString ( ) ; } catch ( final Exception e ) { throw new SamlException ( e . getMessage ( ) , e ) ; } } | Log saml object . |
17,977 | @ GetMapping ( path = WSFederationConstants . ENDPOINT_FEDERATION_METADATA ) public void doGet ( final HttpServletRequest request , final HttpServletResponse response ) throws Exception { try { response . setContentType ( MediaType . TEXT_HTML_VALUE ) ; val out = response . getWriter ( ) ; val metadata = WSFederationMetadataWriter . produceMetadataDocument ( casProperties ) ; out . write ( DOM2Writer . nodeToString ( metadata ) ) ; } catch ( final Exception ex ) { LOGGER . error ( "Failed to get metadata document" , ex ) ; response . sendError ( HttpServletResponse . SC_INTERNAL_SERVER_ERROR ) ; } } | Get Metadata . |
17,978 | public CouchDbConsentDecision copyDetailsFrom ( final ConsentDecision other ) { setAttributes ( other . getAttributes ( ) ) ; setPrincipal ( other . getPrincipal ( ) ) ; setCreatedDate ( other . getCreatedDate ( ) ) ; setId ( other . getId ( ) ) ; setOptions ( other . getOptions ( ) ) ; setReminder ( other . getReminder ( ) ) ; setReminderTimeUnit ( other . getReminderTimeUnit ( ) ) ; setService ( other . getService ( ) ) ; return this ; } | Copy consent details to this instance . |
17,979 | public static OidcClientRegistrationResponse getClientRegistrationResponse ( final OidcRegisteredService registeredService , final String serverPrefix ) { val clientResponse = new OidcClientRegistrationResponse ( ) ; clientResponse . setApplicationType ( registeredService . getApplicationType ( ) ) ; clientResponse . setClientId ( registeredService . getClientId ( ) ) ; clientResponse . setClientSecret ( registeredService . getClientSecret ( ) ) ; clientResponse . setSubjectType ( registeredService . getSubjectType ( ) ) ; clientResponse . setTokenEndpointAuthMethod ( registeredService . getTokenEndpointAuthenticationMethod ( ) ) ; clientResponse . setClientName ( registeredService . getName ( ) ) ; clientResponse . setRedirectUris ( CollectionUtils . wrap ( registeredService . getServiceId ( ) ) ) ; clientResponse . setContacts ( registeredService . getContacts ( ) . stream ( ) . map ( RegisteredServiceContact :: getName ) . filter ( StringUtils :: isNotBlank ) . collect ( Collectors . toList ( ) ) ) ; clientResponse . setGrantTypes ( Arrays . stream ( OAuth20GrantTypes . values ( ) ) . map ( type -> type . getType ( ) . toLowerCase ( ) ) . collect ( Collectors . toList ( ) ) ) ; clientResponse . setResponseTypes ( Arrays . stream ( OAuth20ResponseTypes . values ( ) ) . map ( type -> type . getType ( ) . toLowerCase ( ) ) . collect ( Collectors . toList ( ) ) ) ; val validator = new SimpleUrlValidatorFactoryBean ( false ) . getObject ( ) ; if ( Objects . requireNonNull ( validator ) . isValid ( registeredService . getJwks ( ) ) ) { clientResponse . setJwksUri ( registeredService . getJwks ( ) ) ; } else { val jwks = new JsonWebKeySet ( registeredService . getJwks ( ) ) ; clientResponse . setJwks ( jwks . toJson ( ) ) ; } clientResponse . setLogo ( registeredService . getLogo ( ) ) ; clientResponse . setPolicyUri ( registeredService . getInformationUrl ( ) ) ; clientResponse . setTermsOfUseUri ( registeredService . getPrivacyUrl ( ) ) ; clientResponse . setRedirectUris ( CollectionUtils . wrapList ( registeredService . getServiceId ( ) ) ) ; val clientConfigUri = getClientConfigurationUri ( registeredService , serverPrefix ) ; clientResponse . setRegistrationClientUri ( clientConfigUri ) ; return clientResponse ; } | Gets client registration response . |
17,980 | public static String getClientConfigurationUri ( final OidcRegisteredService registeredService , final String serverPrefix ) throws URISyntaxException { return new URIBuilder ( serverPrefix . concat ( '/' + OidcConstants . BASE_OIDC_URL + '/' + OidcConstants . CLIENT_CONFIGURATION_URL ) ) . addParameter ( OidcConstants . CLIENT_REGISTRATION_CLIENT_ID , registeredService . getClientId ( ) ) . build ( ) . toString ( ) ; } | Gets client configuration uri . |
17,981 | public static ResponseEntity < String > createResponseEntityForAuthnFailure ( final AuthenticationException e , final HttpServletRequest request , final ApplicationContext applicationContext ) { try { val authnExceptions = e . getHandlerErrors ( ) . values ( ) . stream ( ) . map ( ex -> mapExceptionToMessage ( e , request , applicationContext , ex ) ) . collect ( Collectors . toList ( ) ) ; val errorsMap = new HashMap < String , List < String > > ( ) ; errorsMap . put ( "authentication_exceptions" , authnExceptions ) ; LOGGER . warn ( "[{}] Caused by: [{}]" , e . getMessage ( ) , authnExceptions ) ; return new ResponseEntity < > ( MAPPER . writerWithDefaultPrettyPrinter ( ) . writeValueAsString ( errorsMap ) , HttpStatus . UNAUTHORIZED ) ; } catch ( final JsonProcessingException exception ) { LOGGER . error ( e . getMessage ( ) , e ) ; return new ResponseEntity < > ( e . getMessage ( ) , HttpStatus . INTERNAL_SERVER_ERROR ) ; } } | Create response entity for authn failure response . |
17,982 | private static PublicKey createRegisteredServicePublicKey ( final RegisteredService registeredService ) { if ( registeredService . getPublicKey ( ) == null ) { LOGGER . debug ( "No public key is defined for service [{}]. No encoding will take place." , registeredService ) ; return null ; } val publicKey = registeredService . getPublicKey ( ) . createInstance ( ) ; if ( publicKey == null ) { LOGGER . debug ( "No public key instance created for service [{}]. No encoding will take place." , registeredService ) ; return null ; } return publicKey ; } | Create registered service public key defined . |
17,983 | private static Cipher initializeCipherBasedOnServicePublicKey ( final PublicKey publicKey , final RegisteredService registeredService ) { try { LOGGER . debug ( "Using service [{}] public key [{}] to initialize the cipher" , registeredService . getServiceId ( ) , registeredService . getPublicKey ( ) ) ; val cipher = Cipher . getInstance ( publicKey . getAlgorithm ( ) ) ; cipher . init ( Cipher . ENCRYPT_MODE , publicKey ) ; LOGGER . debug ( "Initialized cipher in encrypt-mode via the public key algorithm [{}] for service [{}]" , publicKey . getAlgorithm ( ) , registeredService . getServiceId ( ) ) ; return cipher ; } catch ( final Exception e ) { LOGGER . warn ( "Cipher could not be initialized for service [{}]. Error [{}]" , registeredService , e . getMessage ( ) ) ; } return null ; } | Initialize cipher based on service public key . |
17,984 | public String encode ( final String data , final Optional < RegisteredService > service ) { try { if ( service . isPresent ( ) ) { val registeredService = service . get ( ) ; val publicKey = createRegisteredServicePublicKey ( registeredService ) ; val result = encodeInternal ( data , publicKey , registeredService ) ; if ( result != null ) { return EncodingUtils . encodeBase64 ( result ) ; } } } catch ( final Exception e ) { LOGGER . warn ( e . getMessage ( ) , e ) ; } return null ; } | Encrypt using the given cipher associated with the service and encode the data in base 64 . |
17,985 | protected void loadSamlMetadataIntoRequestContext ( final RequestContext requestContext , final String entityId , final RegisteredService registeredService ) { LOGGER . debug ( "Locating SAML MDUI for entity [{}]" , entityId ) ; val mdui = MetadataUIUtils . locateMetadataUserInterfaceForEntityId ( this . metadataAdapter , entityId , registeredService , WebUtils . getHttpServletRequestFromExternalWebflowContext ( requestContext ) ) ; LOGGER . debug ( "Located SAML MDUI for entity [{}] as [{}]" , entityId , mdui ) ; WebUtils . putServiceUserInterfaceMetadata ( requestContext , mdui ) ; } | Load saml metadata into request context . |
17,986 | protected void verifyRegisteredService ( final RequestContext requestContext , final RegisteredService registeredService ) { if ( registeredService == null || ! registeredService . getAccessStrategy ( ) . isServiceAccessAllowed ( ) ) { LOGGER . debug ( "Service [{}] is not recognized/allowed by the CAS service registry" , registeredService ) ; if ( registeredService != null ) { WebUtils . putUnauthorizedRedirectUrlIntoFlowScope ( requestContext , registeredService . getAccessStrategy ( ) . getUnauthorizedRedirectUrl ( ) ) ; } throw new UnauthorizedServiceException ( UnauthorizedServiceException . CODE_UNAUTHZ_SERVICE , StringUtils . EMPTY ) ; } } | Verify registered service . |
17,987 | protected String getEntityIdFromRequest ( final RequestContext requestContext ) { val request = WebUtils . getHttpServletRequestFromExternalWebflowContext ( requestContext ) ; return request . getParameter ( this . entityIdParameterName ) ; } | Gets entity id from request . |
17,988 | protected boolean locateMatchingHttpRequest ( final Authentication authentication , final HttpServletRequest request ) { if ( StringUtils . isNotBlank ( bypassProperties . getHttpRequestRemoteAddress ( ) ) ) { if ( httpRequestRemoteAddressPattern . matcher ( request . getRemoteAddr ( ) ) . find ( ) ) { LOGGER . debug ( "Http request remote address [{}] matches [{}]" , bypassProperties . getHttpRequestRemoteAddress ( ) , request . getRemoteAddr ( ) ) ; return true ; } if ( httpRequestRemoteAddressPattern . matcher ( request . getRemoteHost ( ) ) . find ( ) ) { LOGGER . debug ( "Http request remote host [{}] matches [{}]" , bypassProperties . getHttpRequestRemoteAddress ( ) , request . getRemoteHost ( ) ) ; return true ; } } if ( StringUtils . isNotBlank ( bypassProperties . getHttpRequestHeaders ( ) ) ) { val headerNames = Collections . list ( request . getHeaderNames ( ) ) ; val matched = this . httpRequestHeaderPatterns . stream ( ) . anyMatch ( pattern -> headerNames . stream ( ) . anyMatch ( name -> pattern . matcher ( name ) . matches ( ) ) ) ; if ( matched ) { LOGGER . debug ( "Http request remote headers [{}] match [{}]" , headerNames , bypassProperties . getHttpRequestHeaders ( ) ) ; return true ; } } return false ; } | Locate matching http request and determine if bypass should be enabled . |
17,989 | public static Document produceMetadataDocument ( final CasConfigurationProperties config ) { try { val wsfedIdp = config . getAuthn ( ) . getWsfedIdp ( ) ; val sts = wsfedIdp . getSts ( ) ; val prop = CryptoUtils . getSecurityProperties ( sts . getRealm ( ) . getKeystoreFile ( ) , sts . getRealm ( ) . getKeystorePassword ( ) , sts . getRealm ( ) . getKeystoreAlias ( ) ) ; val crypto = CryptoFactory . getInstance ( prop ) ; val writer = new W3CDOMStreamWriter ( ) ; writer . writeStartDocument ( StandardCharsets . UTF_8 . name ( ) , "1.0" ) ; val referenceID = IDGenerator . generateID ( "_" ) ; writer . writeStartElement ( "md" , "EntityDescriptor" , SAML2_METADATA_NS ) ; writer . writeAttribute ( "ID" , referenceID ) ; val idpEntityId = config . getServer ( ) . getPrefix ( ) . concat ( WSFederationConstants . ENDPOINT_FEDERATION_REQUEST ) ; writer . writeAttribute ( "entityID" , idpEntityId ) ; writer . writeNamespace ( "md" , SAML2_METADATA_NS ) ; writer . writeNamespace ( "fed" , WS_FEDERATION_NS ) ; writer . writeNamespace ( "wsa" , WS_ADDRESSING_NS ) ; writer . writeNamespace ( "auth" , WS_FEDERATION_NS ) ; writer . writeNamespace ( "xsi" , SCHEMA_INSTANCE_NS ) ; val stsUrl = config . getServer ( ) . getPrefix ( ) . concat ( WSFederationConstants . ENDPOINT_STS ) . concat ( wsfedIdp . getIdp ( ) . getRealmName ( ) ) ; writeFederationMetadata ( writer , idpEntityId , stsUrl , crypto ) ; writer . writeEndElement ( ) ; writer . writeEndDocument ( ) ; writer . close ( ) ; val out = DOM2Writer . nodeToString ( writer . getDocument ( ) ) ; LOGGER . trace ( out ) ; val result = SignatureUtils . signMetaInfo ( crypto , null , sts . getRealm ( ) . getKeyPassword ( ) , writer . getDocument ( ) , referenceID ) ; if ( result != null ) { return result ; } throw new IllegalArgumentException ( "Failed to sign the metadata document" ) ; } catch ( final Exception e ) { throw new IllegalArgumentException ( "Error creating service metadata information: " + e . getMessage ( ) , e ) ; } } | Produce metadata document . |
17,990 | public long delete ( final List < TicketDocument > ticketDocuments ) { return ( long ) db . executeBulk ( ticketDocuments . stream ( ) . map ( BulkDeleteDocument :: of ) . collect ( Collectors . toList ( ) ) ) . size ( ) ; } | Delete tickets . |
17,991 | protected < T extends SAMLObject > void prepareSamlOutboundProtocolMessageSigningHandler ( final MessageContext < T > outboundContext ) throws Exception { LOGGER . trace ( "Attempting to sign the outbound SAML message..." ) ; val handler = new SAMLOutboundProtocolMessageSigningHandler ( ) ; handler . setSignErrorResponses ( casProperties . getAuthn ( ) . getSamlIdp ( ) . getResponse ( ) . isSignError ( ) ) ; handler . invoke ( outboundContext ) ; LOGGER . debug ( "Signed SAML message successfully" ) ; } | Prepare saml outbound protocol message signing handler . |
17,992 | protected < T extends SAMLObject > void prepareSamlOutboundDestinationHandler ( final MessageContext < T > outboundContext ) throws Exception { val handlerDest = new SAMLOutboundDestinationHandler ( ) ; handlerDest . initialize ( ) ; handlerDest . invoke ( outboundContext ) ; } | Prepare saml outbound destination handler . |
17,993 | protected < T extends SAMLObject > void prepareEndpointURLSchemeSecurityHandler ( final MessageContext < T > outboundContext ) throws Exception { val handlerEnd = new EndpointURLSchemeSecurityHandler ( ) ; handlerEnd . initialize ( ) ; handlerEnd . invoke ( outboundContext ) ; } | Prepare endpoint url scheme security handler . |
17,994 | protected < T extends SAMLObject > void prepareSecurityParametersContext ( final SamlRegisteredServiceServiceProviderMetadataFacade adaptor , final MessageContext < T > outboundContext , final SamlRegisteredService service ) { val secParametersContext = outboundContext . getSubcontext ( SecurityParametersContext . class , true ) ; val roleDesc = adaptor . getSsoDescriptor ( ) ; val signingParameters = buildSignatureSigningParameters ( roleDesc , service ) ; secParametersContext . setSignatureSigningParameters ( signingParameters ) ; } | Prepare security parameters context . |
17,995 | protected < T extends SAMLObject > void prepareOutboundContext ( final T samlObject , final SamlRegisteredServiceServiceProviderMetadataFacade adaptor , final MessageContext < T > outboundContext , final String binding , final RequestAbstractType authnRequest ) throws SamlException { LOGGER . trace ( "Outbound saml object to use is [{}]" , samlObject . getClass ( ) . getName ( ) ) ; outboundContext . setMessage ( samlObject ) ; SamlIdPUtils . preparePeerEntitySamlEndpointContext ( authnRequest , outboundContext , adaptor , binding ) ; } | Prepare outbound context . |
17,996 | protected SignatureSigningParameters buildSignatureSigningParameters ( final RoleDescriptor descriptor , final SamlRegisteredService service ) { val criteria = new CriteriaSet ( ) ; val signatureSigningConfiguration = getSignatureSigningConfiguration ( descriptor , service ) ; criteria . add ( new SignatureSigningConfigurationCriterion ( signatureSigningConfiguration ) ) ; criteria . add ( new RoleDescriptorCriterion ( descriptor ) ) ; val resolver = new SAMLMetadataSignatureSigningParametersResolver ( ) ; LOGGER . trace ( "Resolving signature signing parameters for [{}]" , descriptor . getElementQName ( ) . getLocalPart ( ) ) ; val params = resolver . resolveSingle ( criteria ) ; if ( params != null ) { LOGGER . trace ( "Created signature signing parameters." + "\nSignature algorithm: [{}]" + "\nSignature canonicalization algorithm: [{}]" + "\nSignature reference digest methods: [{}]" , params . getSignatureAlgorithm ( ) , params . getSignatureCanonicalizationAlgorithm ( ) , params . getSignatureReferenceDigestMethod ( ) ) ; } else { LOGGER . warn ( "Unable to resolve SignatureSigningParameters, response signing will fail." + " Make sure domain names in IDP metadata URLs and certificates match CAS domain name" ) ; } return params ; } | Build signature signing parameters signature signing parameters . |
17,997 | protected PrivateKey getSigningPrivateKey ( ) throws Exception { val samlIdp = casProperties . getAuthn ( ) . getSamlIdp ( ) ; val signingKey = samlIdPMetadataLocator . getSigningKey ( ) ; val privateKeyFactoryBean = new PrivateKeyFactoryBean ( ) ; privateKeyFactoryBean . setLocation ( signingKey ) ; privateKeyFactoryBean . setAlgorithm ( samlIdp . getMetadata ( ) . getPrivateKeyAlgName ( ) ) ; privateKeyFactoryBean . setSingleton ( false ) ; LOGGER . debug ( "Locating signature signing key from [{}]" , signingKey ) ; return privateKeyFactoryBean . getObject ( ) ; } | Gets signing private key . |
17,998 | public void handleRegisteredServiceExpiredEvent ( final CasRegisteredServiceExpiredEvent event ) { val registeredService = event . getRegisteredService ( ) ; val contacts = registeredService . getContacts ( ) ; val mail = casProperties . getServiceRegistry ( ) . getMail ( ) ; val sms = casProperties . getServiceRegistry ( ) . getSms ( ) ; val serviceName = StringUtils . defaultIfBlank ( registeredService . getName ( ) , registeredService . getServiceId ( ) ) ; if ( communicationsManager . isMailSenderDefined ( ) ) { val message = mail . getFormattedBody ( serviceName ) ; contacts . stream ( ) . filter ( c -> StringUtils . isNotBlank ( c . getEmail ( ) ) ) . forEach ( c -> communicationsManager . email ( mail , c . getEmail ( ) , message ) ) ; } if ( communicationsManager . isSmsSenderDefined ( ) ) { val message = String . format ( sms . getText ( ) , serviceName ) ; contacts . stream ( ) . filter ( c -> StringUtils . isNotBlank ( c . getPhone ( ) ) ) . forEach ( c -> communicationsManager . sms ( sms . getFrom ( ) , c . getPhone ( ) , message ) ) ; } servicesManager . load ( ) ; } | Handle registered service expired event . |
17,999 | public static HttpServletRequest getHttpServletRequestFromRequestAttributes ( ) { try { return ( ( ServletRequestAttributes ) RequestContextHolder . currentRequestAttributes ( ) ) . getRequest ( ) ; } catch ( final Exception e ) { LOGGER . trace ( e . getMessage ( ) , e ) ; } return null ; } | Gets http servlet request from request attributes . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.