idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
18,200
public static void putPasswordResetUsername ( final RequestContext requestContext , final String username ) { val flowScope = requestContext . getFlowScope ( ) ; flowScope . put ( "username" , username ) ; }
Put password reset username .
18,201
public static String getPasswordResetUsername ( final RequestContext requestContext ) { val flowScope = requestContext . getFlowScope ( ) ; return flowScope . getString ( "username" ) ; }
Gets password reset username .
18,202
public static String getPasswordResetToken ( final RequestContext requestContext ) { val flowScope = requestContext . getFlowScope ( ) ; return flowScope . getString ( FLOWSCOPE_PARAMETER_NAME_TOKEN ) ; }
Gets password reset token .
18,203
public static String putPasswordResetPasswordPolicyPattern ( final RequestContext requestContext , final String policyPattern ) { val flowScope = requestContext . getFlowScope ( ) ; return flowScope . getString ( "policyPattern" ) ; }
Put password reset password policy pattern string .
18,204
private static boolean containsAddress ( final InetAddress network , final InetAddress netmask , final InetAddress ip ) { LOGGER . debug ( "Checking IP address: [{}] in [{}] by [{}]" , ip , network , netmask ) ; val networkBytes = network . getAddress ( ) ; val netmaskBytes = netmask . getAddress ( ) ; val ipBytes = ip . getAddress ( ) ; if ( networkBytes . length != netmaskBytes . length || netmaskBytes . length != ipBytes . length ) { LOGGER . debug ( "Network address [{}], subnet mask [{}] and/or host address [{}]" + " have different sizes! (return false ...)" , network , netmask , ip ) ; return false ; } for ( var i = 0 ; i < netmaskBytes . length ; i ++ ) { val mask = netmaskBytes [ i ] & HEX_RIGHT_SHIFT_COEFFICIENT ; if ( ( networkBytes [ i ] & mask ) != ( ipBytes [ i ] & mask ) ) { LOGGER . debug ( "[{}] is not in [{}]/[{}]" , ip , network , netmask ) ; return false ; } } LOGGER . debug ( "[{}] is in [{}]/[{}]" , ip , network , netmask ) ; return true ; }
Checks if a subnet contains a specific IP address .
18,205
public void configureIpNetworkRange ( final String ipAddressRange ) { if ( StringUtils . isNotBlank ( ipAddressRange ) ) { val splitAddress = Splitter . on ( "/" ) . splitToList ( ipAddressRange ) ; if ( splitAddress . size ( ) == 2 ) { val network = splitAddress . get ( 0 ) . trim ( ) ; val netmask = splitAddress . get ( 1 ) . trim ( ) ; try { this . inetNetworkRange = InetAddress . getByName ( network ) ; LOGGER . debug ( "InetAddress network: [{}]" , this . inetNetworkRange . toString ( ) ) ; } catch ( final UnknownHostException e ) { LOGGER . error ( "The network address was not valid: [{}]" , e . getMessage ( ) ) ; } try { this . inetNetmask = InetAddress . getByName ( netmask ) ; LOGGER . debug ( "InetAddress netmask: [{}]" , this . inetNetmask . toString ( ) ) ; } catch ( final UnknownHostException e ) { LOGGER . error ( "The network netmask was not valid: [{}]" , e . getMessage ( ) ) ; } } } }
Sets ip network range .
18,206
protected ModelAndView buildCallbackUrlResponseType ( final AccessTokenRequestDataHolder holder , final String redirectUri , final AccessToken accessToken , final List < NameValuePair > params , final RefreshToken refreshToken , final J2EContext context ) throws Exception { val attributes = holder . getAuthentication ( ) . getAttributes ( ) ; val state = attributes . get ( OAuth20Constants . STATE ) . get ( 0 ) . toString ( ) ; val nonce = attributes . get ( OAuth20Constants . NONCE ) . get ( 0 ) . toString ( ) ; val builder = new URIBuilder ( redirectUri ) ; val stringBuilder = new StringBuilder ( ) ; val timeToLive = accessTokenExpirationPolicy . getTimeToLive ( ) ; stringBuilder . append ( OAuth20Constants . ACCESS_TOKEN ) . append ( '=' ) . append ( accessToken . getId ( ) ) . append ( '&' ) . append ( OAuth20Constants . TOKEN_TYPE ) . append ( '=' ) . append ( OAuth20Constants . TOKEN_TYPE_BEARER ) . append ( '&' ) . append ( OAuth20Constants . EXPIRES_IN ) . append ( '=' ) . append ( timeToLive ) ; if ( refreshToken != null ) { stringBuilder . append ( '&' ) . append ( OAuth20Constants . REFRESH_TOKEN ) . append ( '=' ) . append ( refreshToken . getId ( ) ) ; } params . forEach ( p -> stringBuilder . append ( '&' ) . append ( p . getName ( ) ) . append ( '=' ) . append ( p . getValue ( ) ) ) ; if ( StringUtils . isNotBlank ( state ) ) { stringBuilder . append ( '&' ) . append ( OAuth20Constants . STATE ) . append ( '=' ) . append ( EncodingUtils . urlEncode ( state ) ) ; } if ( StringUtils . isNotBlank ( nonce ) ) { stringBuilder . append ( '&' ) . append ( OAuth20Constants . NONCE ) . append ( '=' ) . append ( EncodingUtils . urlEncode ( nonce ) ) ; } builder . setFragment ( stringBuilder . toString ( ) ) ; val url = builder . toString ( ) ; LOGGER . debug ( "Redirecting to URL [{}]" , url ) ; val parameters = new LinkedHashMap < String , String > ( ) ; parameters . put ( OAuth20Constants . ACCESS_TOKEN , accessToken . getId ( ) ) ; if ( refreshToken != null ) { parameters . put ( OAuth20Constants . REFRESH_TOKEN , refreshToken . getId ( ) ) ; } parameters . put ( OAuth20Constants . EXPIRES_IN , timeToLive . toString ( ) ) ; parameters . put ( OAuth20Constants . STATE , state ) ; parameters . put ( OAuth20Constants . NONCE , nonce ) ; parameters . put ( OAuth20Constants . CLIENT_ID , accessToken . getClientId ( ) ) ; return buildResponseModelAndView ( context , servicesManager , accessToken . getClientId ( ) , url , parameters ) ; }
Build callback url response type string .
18,207
public Event doExecute ( final RequestContext requestContext ) { val tgtId = WebUtils . getTicketGrantingTicketId ( requestContext ) ; if ( StringUtils . isBlank ( tgtId ) ) { return new Event ( this , CasWebflowConstants . TRANSITION_ID_TGT_NOT_EXISTS ) ; } try { val ticket = this . centralAuthenticationService . getTicket ( tgtId , Ticket . class ) ; if ( ticket != null && ! ticket . isExpired ( ) ) { return new Event ( this , CasWebflowConstants . TRANSITION_ID_TGT_VALID ) ; } } catch ( final AbstractTicketException e ) { LOGGER . trace ( "Could not retrieve ticket id [{}] from registry." , e . getMessage ( ) ) ; } return new Event ( this , CasWebflowConstants . TRANSITION_ID_TGT_INVALID ) ; }
Determines whether the TGT in the flow request context is valid .
18,208
private static boolean isCritical ( final X509Certificate certificate , final String extensionOid ) { val criticalOids = certificate . getCriticalExtensionOIDs ( ) ; if ( criticalOids == null || criticalOids . isEmpty ( ) ) { return false ; } return criticalOids . contains ( extensionOid ) ; }
Checks if critical extension oids contain the extension oid .
18,209
private static boolean doesNameMatchPattern ( final Principal principal , final Pattern pattern ) { if ( pattern != null ) { val name = principal . getName ( ) ; val result = pattern . matcher ( name ) . matches ( ) ; LOGGER . debug ( "[{}] matches [{}] == [{}]" , pattern . pattern ( ) , name , result ) ; return result ; } return true ; }
Does principal name match pattern?
18,210
private void validate ( final X509Certificate cert ) throws GeneralSecurityException { cert . checkValidity ( ) ; this . revocationChecker . check ( cert ) ; val pathLength = cert . getBasicConstraints ( ) ; if ( pathLength < 0 ) { if ( ! isCertificateAllowed ( cert ) ) { throw new FailedLoginException ( "Certificate subject does not match pattern " + this . regExSubjectDnPattern . pattern ( ) ) ; } if ( this . checkKeyUsage && ! isValidKeyUsage ( cert ) ) { throw new FailedLoginException ( "Certificate keyUsage constraint forbids SSL client authentication." ) ; } } else { if ( pathLength == Integer . MAX_VALUE && ! this . maxPathLengthAllowUnspecified ) { throw new FailedLoginException ( "Unlimited certificate path length not allowed by configuration." ) ; } if ( pathLength > this . maxPathLength && pathLength < Integer . MAX_VALUE ) { throw new FailedLoginException ( String . format ( "Certificate path length %s exceeds maximum value %s." , pathLength , this . maxPathLength ) ) ; } } }
Validate the X509Certificate received .
18,211
public void handleCasRegisteredServiceLoadedEvent ( final CasRegisteredServiceLoadedEvent event ) { LOGGER . trace ( "Received event [{}]" , event ) ; this . publisher . publish ( event . getRegisteredService ( ) , event ) ; }
Handle cas registered service loaded event .
18,212
public void handleCasRegisteredServiceSavedEvent ( final CasRegisteredServiceSavedEvent event ) { LOGGER . trace ( "Received event [{}]" , event ) ; this . publisher . publish ( event . getRegisteredService ( ) , event ) ; }
Handle cas registered service saved event .
18,213
public void handleCasRegisteredServiceDeletedEvent ( final CasRegisteredServiceDeletedEvent event ) { LOGGER . trace ( "Received event [{}]" , event ) ; this . publisher . publish ( event . getRegisteredService ( ) , event ) ; }
Handle cas registered service deleted event .
18,214
public void handleConfigurationModifiedEvent ( final CasConfigurationModifiedEvent event ) { if ( this . contextRefresher == null ) { LOGGER . warn ( "Unable to refresh application context, since no refresher is available" ) ; return ; } if ( event . isEligibleForContextRefresh ( ) ) { LOGGER . info ( "Received event [{}]. Refreshing CAS configuration..." , event ) ; Collection < String > keys = null ; try { keys = contextRefresher . refresh ( ) ; LOGGER . debug ( "Refreshed the following settings: [{}]." , keys ) ; } catch ( final Exception e ) { LOGGER . trace ( e . getMessage ( ) , e ) ; } finally { rebind ( ) ; LOGGER . info ( "CAS finished rebinding configuration with new settings [{}]" , ObjectUtils . defaultIfNull ( keys , new ArrayList < > ( 0 ) ) ) ; } } }
Handle configuration modified event .
18,215
protected void configureEncryptionKeyFromPublicKeyResource ( final String secretKeyToUse ) { val object = extractPublicKeyFromResource ( secretKeyToUse ) ; LOGGER . debug ( "Located encryption key resource [{}]" , secretKeyToUse ) ; setSecretKeyEncryptionKey ( object ) ; setEncryptionAlgorithm ( KeyManagementAlgorithmIdentifiers . RSA_OAEP_256 ) ; }
Configure encryption key from public key resource .
18,216
protected Map < String , List < Object > > getUserInfoFromIndexResult ( final ListIndexResult indexResult ) { val attachment = indexResult . getIndexAttachments ( ) . stream ( ) . findFirst ( ) . orElse ( null ) ; if ( attachment == null ) { LOGGER . warn ( "Index result has no attachments" ) ; return null ; } val identifier = attachment . getObjectIdentifier ( ) ; val listObjectAttributesRequest = CloudDirectoryUtils . getListObjectAttributesRequest ( properties . getDirectoryArn ( ) , identifier ) ; if ( listObjectAttributesRequest == null ) { LOGGER . warn ( "No object attribute request is available for identifier [{}]" , identifier ) ; return null ; } val attributesResult = amazonCloudDirectory . listObjectAttributes ( listObjectAttributesRequest ) ; if ( attributesResult == null || attributesResult . getAttributes ( ) == null || attributesResult . getAttributes ( ) . isEmpty ( ) ) { LOGGER . warn ( "No object attribute result is available for identifier [{}] or not attributes are found" , identifier ) ; return null ; } return attributesResult . getAttributes ( ) . stream ( ) . map ( a -> { var value = ( Object ) null ; val attributeValue = a . getValue ( ) ; LOGGER . debug ( "Examining attribute [{}]" , a ) ; if ( StringUtils . isNotBlank ( attributeValue . getNumberValue ( ) ) ) { value = attributeValue . getNumberValue ( ) ; } else if ( attributeValue . getDatetimeValue ( ) != null ) { value = DateTimeUtils . zonedDateTimeOf ( attributeValue . getDatetimeValue ( ) ) . toString ( ) ; } else if ( attributeValue . getBooleanValue ( ) != null ) { value = attributeValue . getBooleanValue ( ) . toString ( ) ; } else if ( attributeValue . getBinaryValue ( ) != null ) { value = new String ( attributeValue . getBinaryValue ( ) . array ( ) , StandardCharsets . UTF_8 ) ; } else if ( StringUtils . isNotBlank ( attributeValue . getStringValue ( ) ) ) { value = attributeValue . getStringValue ( ) ; } return Pair . of ( a . getKey ( ) . getName ( ) , value ) ; } ) . filter ( p -> p . getValue ( ) != null ) . collect ( Collectors . toMap ( Pair :: getKey , s -> CollectionUtils . toCollection ( s . getValue ( ) , ArrayList . class ) ) ) ; }
Gets user info from index result .
18,217
private static String getRelativeRedirectUrlFor ( final WsFederationConfiguration config , final Service service , final HttpServletRequest request ) { val builder = new URIBuilder ( WsFederationNavigationController . ENDPOINT_REDIRECT ) ; builder . addParameter ( WsFederationNavigationController . PARAMETER_NAME , config . getId ( ) ) ; if ( service != null ) { builder . addParameter ( CasProtocolConstants . PARAMETER_SERVICE , service . getId ( ) ) ; } val method = request . getParameter ( CasProtocolConstants . PARAMETER_METHOD ) ; if ( StringUtils . isNotBlank ( method ) ) { builder . addParameter ( CasProtocolConstants . PARAMETER_METHOD , method ) ; } return builder . toString ( ) ; }
Gets redirect url for .
18,218
public Event buildAuthenticationRequestEvent ( final RequestContext context ) { val clients = new ArrayList < WsFedClient > ( ) ; val request = WebUtils . getHttpServletRequestFromExternalWebflowContext ( context ) ; val service = ( Service ) context . getFlowScope ( ) . get ( CasProtocolConstants . PARAMETER_SERVICE ) ; this . configurations . forEach ( cfg -> { val c = new WsFedClient ( ) ; c . setName ( cfg . getName ( ) ) ; val id = UUID . randomUUID ( ) . toString ( ) ; val rpId = wsFederationHelper . getRelyingPartyIdentifier ( service , cfg ) ; c . setAuthorizationUrl ( cfg . getAuthorizationUrl ( rpId , id ) ) ; c . setReplyingPartyId ( rpId ) ; c . setId ( id ) ; c . setRedirectUrl ( getRelativeRedirectUrlFor ( cfg , service , request ) ) ; c . setAutoRedirect ( cfg . isAutoRedirect ( ) ) ; clients . add ( c ) ; if ( cfg . isAutoRedirect ( ) ) { WebUtils . putDelegatedAuthenticationProviderPrimary ( context , cfg ) ; } } ) ; context . getFlowScope ( ) . put ( PARAMETER_NAME_WSFED_CLIENTS , clients ) ; return new EventFactorySupport ( ) . event ( this , CasWebflowConstants . TRANSITION_ID_PROCEED ) ; }
Build authentication request event event .
18,219
public < T > T execute ( final String methodName , final Class < T > clazz , final Object ... args ) { return execute ( methodName , clazz , true , args ) ; }
Execute t .
18,220
protected String getRemoteHostName ( final String remoteIp ) { val revDNS = new ReverseDNSRunnable ( remoteIp ) ; val t = new Thread ( revDNS ) ; t . start ( ) ; try { t . join ( this . timeout ) ; } catch ( final InterruptedException e ) { LOGGER . debug ( "Threaded lookup failed. Defaulting to IP [{}]." , remoteIp , e ) ; } val remoteHostName = revDNS . getHostName ( ) ; LOGGER . debug ( "Found remote host name [{}]." , remoteHostName ) ; return StringUtils . isNotBlank ( remoteHostName ) ? remoteHostName : remoteIp ; }
Convenience method to perform a reverse DNS lookup . Threads the request through a custom Runnable class in order to prevent inordinately long user waits while performing reverse lookup .
18,221
private static SignatureTrustEngine buildSignatureTrustEngine ( final WsFederationConfiguration wsFederationConfiguration ) { val signingWallet = wsFederationConfiguration . getSigningWallet ( ) ; LOGGER . debug ( "Building signature trust engine based on the following signing certificates:" ) ; signingWallet . forEach ( c -> LOGGER . debug ( "Credential entity id [{}] with public key [{}]" , c . getEntityId ( ) , c . getPublicKey ( ) ) ) ; val resolver = new StaticCredentialResolver ( signingWallet ) ; val keyResolver = new StaticKeyInfoCredentialResolver ( signingWallet ) ; return new ExplicitKeySignatureTrustEngine ( resolver , keyResolver ) ; }
Build signature trust engine .
18,222
private static Credential getEncryptionCredential ( final WsFederationConfiguration config ) { LOGGER . debug ( "Locating encryption credential private key [{}]" , config . getEncryptionPrivateKey ( ) ) ; val br = new BufferedReader ( new InputStreamReader ( config . getEncryptionPrivateKey ( ) . getInputStream ( ) , StandardCharsets . UTF_8 ) ) ; Security . addProvider ( new BouncyCastleProvider ( ) ) ; LOGGER . debug ( "Parsing credential private key" ) ; try ( val pemParser = new PEMParser ( br ) ) { val privateKeyPemObject = pemParser . readObject ( ) ; val converter = new JcaPEMKeyConverter ( ) . setProvider ( new BouncyCastleProvider ( ) ) ; val kp = FunctionUtils . doIf ( Predicates . instanceOf ( PEMEncryptedKeyPair . class ) , Unchecked . supplier ( ( ) -> { LOGGER . debug ( "Encryption private key is an encrypted keypair" ) ; val ckp = ( PEMEncryptedKeyPair ) privateKeyPemObject ; val decProv = new JcePEMDecryptorProviderBuilder ( ) . build ( config . getEncryptionPrivateKeyPassword ( ) . toCharArray ( ) ) ; LOGGER . debug ( "Attempting to decrypt the encrypted keypair based on the provided encryption private key password" ) ; return converter . getKeyPair ( ckp . decryptKeyPair ( decProv ) ) ; } ) , Unchecked . supplier ( ( ) -> { LOGGER . debug ( "Extracting a keypair from the private key" ) ; return converter . getKeyPair ( ( PEMKeyPair ) privateKeyPemObject ) ; } ) ) . apply ( privateKeyPemObject ) ; val certParser = new X509CertParser ( ) ; LOGGER . debug ( "Locating encryption certificate [{}]" , config . getEncryptionCertificate ( ) ) ; certParser . engineInit ( config . getEncryptionCertificate ( ) . getInputStream ( ) ) ; LOGGER . debug ( "Invoking certificate engine to parse the certificate [{}]" , config . getEncryptionCertificate ( ) ) ; val cert = ( X509CertificateObject ) certParser . engineRead ( ) ; LOGGER . debug ( "Creating final credential based on the certificate [{}] and the private key" , cert . getIssuerDN ( ) ) ; return new BasicX509Credential ( cert , kp . getPrivate ( ) ) ; } }
Gets encryption credential . The encryption private key will need to contain the private keypair in PEM format . The encryption certificate is shared with ADFS in DER format i . e certificate . crt .
18,223
public WsFederationCredential createCredentialFromToken ( final Assertion assertion ) { val retrievedOn = ZonedDateTime . now ( ZoneOffset . UTC ) ; LOGGER . debug ( "Retrieved on [{}]" , retrievedOn ) ; val credential = new WsFederationCredential ( ) ; credential . setRetrievedOn ( retrievedOn ) ; credential . setId ( assertion . getID ( ) ) ; credential . setIssuer ( assertion . getIssuer ( ) ) ; credential . setIssuedOn ( ZonedDateTime . parse ( assertion . getIssueInstant ( ) . toDateTimeISO ( ) . toString ( ) ) ) ; val conditions = assertion . getConditions ( ) ; if ( conditions != null ) { credential . setNotBefore ( ZonedDateTime . parse ( conditions . getNotBefore ( ) . toDateTimeISO ( ) . toString ( ) ) ) ; credential . setNotOnOrAfter ( ZonedDateTime . parse ( conditions . getNotOnOrAfter ( ) . toDateTimeISO ( ) . toString ( ) ) ) ; if ( ! conditions . getAudienceRestrictionConditions ( ) . isEmpty ( ) ) { credential . setAudience ( conditions . getAudienceRestrictionConditions ( ) . get ( 0 ) . getAudiences ( ) . get ( 0 ) . getUri ( ) ) ; } } if ( ! assertion . getAuthenticationStatements ( ) . isEmpty ( ) ) { credential . setAuthenticationMethod ( assertion . getAuthenticationStatements ( ) . get ( 0 ) . getAuthenticationMethod ( ) ) ; } val attributes = new HashMap < String , List < Object > > ( ) ; assertion . getAttributeStatements ( ) . stream ( ) . flatMap ( attributeStatement -> attributeStatement . getAttributes ( ) . stream ( ) ) . forEach ( item -> { LOGGER . debug ( "Processed attribute: [{}]" , item . getAttributeName ( ) ) ; final List < Object > itemList = item . getAttributeValues ( ) . stream ( ) . map ( xmlObject -> ( ( XSAny ) xmlObject ) . getTextContent ( ) ) . collect ( Collectors . toList ( ) ) ; if ( ! itemList . isEmpty ( ) ) { attributes . put ( item . getAttributeName ( ) , itemList ) ; } } ) ; credential . setAttributes ( attributes ) ; LOGGER . debug ( "Credential: [{}]" , credential ) ; return credential ; }
createCredentialFromToken converts a SAML 1 . 1 assertion to a WSFederationCredential .
18,224
public RequestedSecurityToken getRequestSecurityTokenFromResult ( final String wresult ) { LOGGER . debug ( "Result token received from ADFS is [{}]" , wresult ) ; try ( InputStream in = new ByteArrayInputStream ( wresult . getBytes ( StandardCharsets . UTF_8 ) ) ) { LOGGER . debug ( "Parsing token into a document" ) ; val document = configBean . getParserPool ( ) . parse ( in ) ; val metadataRoot = document . getDocumentElement ( ) ; val unmarshallerFactory = configBean . getUnmarshallerFactory ( ) ; val unmarshaller = unmarshallerFactory . getUnmarshaller ( metadataRoot ) ; if ( unmarshaller == null ) { throw new IllegalArgumentException ( "Unmarshaller for the metadata root element cannot be determined" ) ; } LOGGER . debug ( "Unmarshalling the document into a security token response" ) ; val rsToken = ( RequestSecurityTokenResponse ) unmarshaller . unmarshall ( metadataRoot ) ; if ( rsToken . getRequestedSecurityToken ( ) == null ) { throw new IllegalArgumentException ( "Request security token response is null" ) ; } LOGGER . debug ( "Locating list of requested security tokens" ) ; val rst = rsToken . getRequestedSecurityToken ( ) ; if ( rst . isEmpty ( ) ) { throw new IllegalArgumentException ( "No requested security token response is provided in the response" ) ; } LOGGER . debug ( "Locating the first occurrence of a requested security token in the list" ) ; val reqToken = rst . get ( 0 ) ; if ( reqToken . getSecurityTokens ( ) == null || reqToken . getSecurityTokens ( ) . isEmpty ( ) ) { throw new IllegalArgumentException ( "Requested security token response is not carrying any security tokens" ) ; } return reqToken ; } catch ( final Exception ex ) { LOGGER . error ( ex . getMessage ( ) , ex ) ; } return null ; }
Gets request security token response from result .
18,225
public Pair < Assertion , WsFederationConfiguration > buildAndVerifyAssertion ( final RequestedSecurityToken reqToken , final Collection < WsFederationConfiguration > config ) { val securityToken = getSecurityTokenFromRequestedToken ( reqToken , config ) ; if ( securityToken instanceof Assertion ) { LOGGER . debug ( "Security token is an assertion." ) ; val assertion = Assertion . class . cast ( securityToken ) ; LOGGER . debug ( "Extracted assertion successfully: [{}]" , assertion ) ; val cfg = config . stream ( ) . filter ( c -> c . getIdentityProviderIdentifier ( ) . equals ( assertion . getIssuer ( ) ) ) . findFirst ( ) . orElse ( null ) ; if ( cfg == null ) { throw new IllegalArgumentException ( "Could not locate wsfed configuration for security token provided. The assertion issuer " + assertion . getIssuer ( ) + " does not match any of the identity provider identifiers defined in the configuration" ) ; } return Pair . of ( assertion , cfg ) ; } throw new IllegalArgumentException ( "Could not extract or decrypt an assertion based on the security token provided" ) ; }
converts a token into an assertion .
18,226
public boolean validateSignature ( final Pair < Assertion , WsFederationConfiguration > resultPair ) { if ( resultPair == null ) { LOGGER . warn ( "No assertion or its configuration was provided to validate signatures" ) ; return false ; } val configuration = resultPair . getValue ( ) ; val assertion = resultPair . getKey ( ) ; if ( assertion == null || configuration == null ) { LOGGER . warn ( "No signature or configuration was provided to validate signatures" ) ; return false ; } val signature = assertion . getSignature ( ) ; if ( signature == null ) { LOGGER . warn ( "No signature is attached to the assertion to validate" ) ; return false ; } try { LOGGER . debug ( "Validating the signature..." ) ; val validator = new SAMLSignatureProfileValidator ( ) ; validator . validate ( signature ) ; val criteriaSet = new CriteriaSet ( ) ; criteriaSet . add ( new UsageCriterion ( UsageType . SIGNING ) ) ; criteriaSet . add ( new EntityRoleCriterion ( IDPSSODescriptor . DEFAULT_ELEMENT_NAME ) ) ; criteriaSet . add ( new ProtocolCriterion ( SAMLConstants . SAML20P_NS ) ) ; criteriaSet . add ( new EntityIdCriterion ( configuration . getIdentityProviderIdentifier ( ) ) ) ; try { val engine = buildSignatureTrustEngine ( configuration ) ; LOGGER . debug ( "Validating signature via trust engine for [{}]" , configuration . getIdentityProviderIdentifier ( ) ) ; return engine . validate ( signature , criteriaSet ) ; } catch ( final SecurityException e ) { LOGGER . warn ( e . getMessage ( ) , e ) ; } } catch ( final SignatureException e ) { LOGGER . error ( "Failed to validate assertion signature" , e ) ; } SamlUtils . logSamlObject ( this . configBean , assertion ) ; LOGGER . error ( "Signature doesn't match any signing credential and cannot be validated." ) ; return false ; }
validateSignature checks to see if the signature on an assertion is valid .
18,227
public String getRelyingPartyIdentifier ( final Service service , final WsFederationConfiguration configuration ) { val relyingPartyIdentifier = configuration . getRelyingPartyIdentifier ( ) ; if ( service != null ) { val registeredService = this . servicesManager . findServiceBy ( service ) ; RegisteredServiceAccessStrategyUtils . ensureServiceAccessIsAllowed ( service , registeredService ) ; if ( RegisteredServiceProperty . RegisteredServiceProperties . WSFED_RELYING_PARTY_ID . isAssignedTo ( registeredService ) ) { LOGGER . debug ( "Determined relying party identifier from service [{}] to be [{}]" , service , relyingPartyIdentifier ) ; return RegisteredServiceProperty . RegisteredServiceProperties . WSFED_RELYING_PARTY_ID . getPropertyValue ( registeredService ) . getValue ( ) ; } } LOGGER . debug ( "Determined relying party identifier to be [{}]" , relyingPartyIdentifier ) ; return relyingPartyIdentifier ; }
Get the relying party id for a service .
18,228
private static Credential getSigningCredential ( final Resource resource ) { try ( val inputStream = resource . getInputStream ( ) ) { val certificateFactory = CertificateFactory . getInstance ( "X.509" ) ; val certificate = ( X509Certificate ) certificateFactory . generateCertificate ( inputStream ) ; val publicCredential = new BasicX509Credential ( certificate ) ; LOGGER . debug ( "Signing credential key retrieved from [{}]." , resource ) ; return publicCredential ; } catch ( final Exception ex ) { LOGGER . error ( ex . getMessage ( ) , ex ) ; } return null ; }
getSigningCredential loads up an X509Credential from a file .
18,229
public String getAuthorizationUrl ( final String relyingPartyIdentifier , final String wctx ) { return String . format ( getIdentityProviderUrl ( ) + QUERYSTRING , relyingPartyIdentifier , wctx ) ; }
Gets authorization url .
18,230
protected String getRenderedUserProfile ( final Map < String , Object > model ) { if ( oauthProperties . getUserProfileViewType ( ) == OAuthProperties . UserProfileViewTypes . FLAT ) { val flattened = new LinkedHashMap < String , Object > ( ) ; if ( model . containsKey ( MODEL_ATTRIBUTE_ATTRIBUTES ) ) { val attributes = Map . class . cast ( model . get ( MODEL_ATTRIBUTE_ATTRIBUTES ) ) ; flattened . putAll ( attributes ) ; } model . keySet ( ) . stream ( ) . filter ( k -> ! k . equalsIgnoreCase ( MODEL_ATTRIBUTE_ATTRIBUTES ) ) . forEach ( k -> flattened . put ( k , model . get ( k ) ) ) ; LOGGER . trace ( "Flattened user profile attributes with the final model as [{}]" , model ) ; return OAuth20Utils . toJson ( flattened ) ; } return OAuth20Utils . toJson ( model ) ; }
Gets rendered user profile .
18,231
public static Map < String , Object > buildEventAttributeMap ( final Principal principal , final Optional < RegisteredService > service , final MultifactorAuthenticationProvider provider ) { val map = new HashMap < String , Object > ( ) ; map . put ( Principal . class . getName ( ) , principal ) ; service . ifPresent ( svc -> map . put ( RegisteredService . class . getName ( ) , svc ) ) ; map . put ( MultifactorAuthenticationProvider . class . getName ( ) , provider ) ; return map ; }
Build event attribute map map .
18,232
public static Event validateEventIdForMatchingTransitionInContext ( final String eventId , final Optional < RequestContext > context , final Map < String , Object > attributes ) { val attributesMap = new LocalAttributeMap < Object > ( attributes ) ; val event = new Event ( eventId , eventId , attributesMap ) ; return context . map ( ctx -> { val def = ctx . getMatchingTransition ( event . getId ( ) ) ; if ( def == null ) { throw new AuthenticationException ( "Transition definition cannot be found for event " + event . getId ( ) ) ; } return event ; } ) . orElse ( event ) ; }
Validate event id for matching transition in context event .
18,233
public static Set < Event > resolveEventViaMultivaluedAttribute ( final Principal principal , final Object attributeValue , final RegisteredService service , final Optional < RequestContext > context , final MultifactorAuthenticationProvider provider , final Predicate < String > predicate ) { val events = new HashSet < Event > ( ) ; if ( attributeValue instanceof Collection ) { val values = ( Collection < String > ) attributeValue ; values . forEach ( value -> { try { if ( predicate . test ( value ) ) { val id = provider . getId ( ) ; val event = validateEventIdForMatchingTransitionInContext ( id , context , buildEventAttributeMap ( principal , Optional . of ( service ) , provider ) ) ; events . add ( event ) ; } } catch ( final Exception e ) { LOGGER . debug ( "Ignoring [{}] since no matching transition could be found" , value ) ; } } ) ; return events ; } return null ; }
Resolve event via multivalued attribute set .
18,234
public static Set < Event > resolveEventViaSingleAttribute ( final Principal principal , final Object attributeValue , final RegisteredService service , final Optional < RequestContext > context , final MultifactorAuthenticationProvider provider , final Predicate < String > predicate ) { if ( ! ( attributeValue instanceof Collection ) ) { LOGGER . debug ( "Attribute value [{}] is a single-valued attribute" , attributeValue ) ; if ( predicate . test ( attributeValue . toString ( ) ) ) { LOGGER . debug ( "Attribute value predicate [{}] has matched the [{}]" , predicate , attributeValue ) ; return evaluateEventForProviderInContext ( principal , service , context , provider ) ; } LOGGER . debug ( "Attribute value predicate [{}] could not match the [{}]" , predicate , attributeValue ) ; } LOGGER . debug ( "Attribute value [{}] is not a single-valued attribute" , attributeValue ) ; return null ; }
Resolve event via single attribute set .
18,235
public Collection < MultifactorAuthenticationProvider > getAuthenticationProviderForService ( final RegisteredService service ) { val policy = service . getMultifactorPolicy ( ) ; if ( policy != null ) { return policy . getMultifactorAuthenticationProviders ( ) . stream ( ) . map ( MultifactorAuthenticationUtils :: getMultifactorAuthenticationProviderFromApplicationContext ) . filter ( Optional :: isPresent ) . map ( Optional :: get ) . collect ( Collectors . toSet ( ) ) ; } return null ; }
Gets authentication provider for service .
18,236
public static Set < Event > evaluateEventForProviderInContext ( final Principal principal , final RegisteredService service , final Optional < RequestContext > context , final MultifactorAuthenticationProvider provider ) { LOGGER . debug ( "Attempting check for availability of multifactor authentication provider [{}] for [{}]" , provider , service ) ; if ( provider != null ) { LOGGER . debug ( "Provider [{}] is successfully verified" , provider ) ; val id = provider . getId ( ) ; val event = MultifactorAuthenticationUtils . validateEventIdForMatchingTransitionInContext ( id , context , MultifactorAuthenticationUtils . buildEventAttributeMap ( principal , Optional . of ( service ) , provider ) ) ; return CollectionUtils . wrapSet ( event ) ; } LOGGER . debug ( "Provider could not be verified" ) ; return new HashSet < > ( 0 ) ; }
Evaluate event for provider in context set .
18,237
public static Map < String , MultifactorAuthenticationProvider > getAvailableMultifactorAuthenticationProviders ( final ApplicationContext applicationContext ) { try { return applicationContext . getBeansOfType ( MultifactorAuthenticationProvider . class , false , true ) ; } catch ( final Exception e ) { LOGGER . trace ( "No beans of type [{}] are available in the application context. " + "CAS may not be configured to handle multifactor authentication requests in absence of a provider" , MultifactorAuthenticationProvider . class ) ; } return new HashMap < > ( 0 ) ; }
Gets all multifactor authentication providers from application context .
18,238
protected String determineConsentEvent ( final RequestContext requestContext ) { val webService = WebUtils . getService ( requestContext ) ; val service = this . authenticationRequestServiceSelectionStrategies . resolveService ( webService ) ; if ( service == null ) { return null ; } val registeredService = getRegisteredServiceForConsent ( requestContext , service ) ; val authentication = WebUtils . getAuthentication ( requestContext ) ; if ( authentication == null ) { return null ; } return isConsentRequired ( service , registeredService , authentication , requestContext ) ; }
Determine consent event string .
18,239
protected String isConsentRequired ( final Service service , final RegisteredService registeredService , final Authentication authentication , final RequestContext requestContext ) { val required = this . consentEngine . isConsentRequiredFor ( service , registeredService , authentication ) . isRequired ( ) ; return required ? EVENT_ID_CONSENT_REQUIRED : null ; }
Is consent required ?
18,240
public String getDescription ( ) { val items = getDescriptions ( ) ; if ( items . isEmpty ( ) ) { return this . registeredService . getDescription ( ) ; } return StringUtils . collectionToDelimitedString ( items , "." ) ; }
Gets description .
18,241
public String getDisplayName ( ) { val items = getDisplayNames ( ) ; if ( items . isEmpty ( ) ) { return this . registeredService . getName ( ) ; } return StringUtils . collectionToDelimitedString ( items , "." ) ; }
Gets display name .
18,242
public String getInformationURL ( ) { val items = getInformationURLs ( ) ; if ( items . isEmpty ( ) ) { return this . registeredService . getInformationUrl ( ) ; } return StringUtils . collectionToDelimitedString ( items , "." ) ; }
Gets information uRL .
18,243
public String getPrivacyStatementURL ( ) { val items = getPrivacyStatementURLs ( ) ; if ( items . isEmpty ( ) ) { return this . registeredService . getPrivacyUrl ( ) ; } return StringUtils . collectionToDelimitedString ( items , "." ) ; }
Gets privacy statement uRL .
18,244
public String getLogoUrl ( ) { try { val items = getLogoUrls ( ) ; if ( ! items . isEmpty ( ) ) { return items . iterator ( ) . next ( ) . getUrl ( ) ; } } catch ( final Exception e ) { LOGGER . debug ( e . getMessage ( ) , e ) ; } return this . registeredService . getLogo ( ) ; }
Gets logo url .
18,245
protected String getRegisteredServiceJwtProperty ( final RegisteredService service , final RegisteredServiceProperty . RegisteredServiceProperties propName ) { if ( service == null || ! service . getAccessStrategy ( ) . isServiceAccessAllowed ( ) ) { LOGGER . debug ( "Service is not defined/found or its access is disabled in the registry" ) ; throw new UnauthorizedServiceException ( UnauthorizedServiceException . CODE_UNAUTHZ_SERVICE ) ; } if ( propName . isAssignedTo ( service ) ) { return propName . getPropertyValue ( service ) . getValue ( ) ; } LOGGER . warn ( "Service [{}] does not define a property [{}] in the registry" , service . getServiceId ( ) , propName ) ; return null ; }
Gets registered service jwt secret .
18,246
private RegisteredService update ( final RegisteredService rs ) { val currentDn = getCurrentDnForRegisteredService ( rs ) ; if ( StringUtils . isNotBlank ( currentDn ) ) { LOGGER . debug ( "Updating registered service at [{}]" , currentDn ) ; val entry = this . ldapServiceMapper . mapFromRegisteredService ( this . baseDn , rs ) ; LdapUtils . executeModifyOperation ( currentDn , this . connectionFactory , entry ) ; } else { LOGGER . debug ( "Failed to locate DN for registered service by id [{}]. Attempting to save the service anew" , rs . getId ( ) ) ; insert ( rs ) ; } return rs ; }
Update the ldap entry with the given registered service .
18,247
public CouchDbGoogleAuthenticatorAccount update ( final OneTimeTokenAccount account ) { setId ( account . getId ( ) ) ; setUsername ( account . getUsername ( ) ) ; setSecretKey ( account . getSecretKey ( ) ) ; setValidationCode ( account . getValidationCode ( ) ) ; setScratchCodes ( account . getScratchCodes ( ) ) ; setRegistrationDate ( account . getRegistrationDate ( ) ) ; return this ; }
Update account info from account object .
18,248
private static void putGoogleAnalyticsTrackingIdIntoFlowScope ( final RequestContext context , final String value ) { if ( StringUtils . isBlank ( value ) ) { context . getFlowScope ( ) . remove ( ATTRIBUTE_FLOWSCOPE_GOOGLE_ANALYTICS_TRACKING_ID ) ; } else { context . getFlowScope ( ) . put ( ATTRIBUTE_FLOWSCOPE_GOOGLE_ANALYTICS_TRACKING_ID , value ) ; } }
Put tracking id into flow scope .
18,249
public static StringValueResolver prepScheduledAnnotationBeanPostProcessor ( final ApplicationContext applicationContext ) { val resolver = new CasEmbeddedValueResolver ( applicationContext ) ; try { val sch = applicationContext . getBean ( ScheduledAnnotationBeanPostProcessor . class ) ; sch . setEmbeddedValueResolver ( resolver ) ; } catch ( final NoSuchBeanDefinitionException e ) { LOGGER . warn ( "Unable to locate [ScheduledAnnotationBeanPostProcessor] as a bean. Support for duration syntax (i.e. PT2S) may not be available" ) ; LOGGER . trace ( e . getMessage ( ) , e ) ; } return resolver ; }
Gets string value resolver .
18,250
public String build ( final RegisteredService service , final String extension ) { return StringUtils . remove ( service . getName ( ) , ' ' ) + '-' + service . getId ( ) + '.' + extension ; }
Method creates a filename to store the service .
18,251
public void verifySamlProfileRequestIfNeeded ( final RequestAbstractType profileRequest , final MetadataResolver resolver , final HttpServletRequest request , final MessageContext context ) throws Exception { val roleDescriptorResolver = getRoleDescriptorResolver ( resolver , context , profileRequest ) ; LOGGER . debug ( "Validating signature for [{}]" , profileRequest . getClass ( ) . getName ( ) ) ; val signature = profileRequest . getSignature ( ) ; if ( signature != null ) { validateSignatureOnProfileRequest ( profileRequest , signature , roleDescriptorResolver ) ; } else { validateSignatureOnAuthenticationRequest ( profileRequest , request , context , roleDescriptorResolver ) ; } }
Verify saml profile request if needed .
18,252
public void verifySamlProfileRequestIfNeeded ( final RequestAbstractType profileRequest , final SamlRegisteredServiceServiceProviderMetadataFacade adaptor , final HttpServletRequest request , final MessageContext context ) throws Exception { verifySamlProfileRequestIfNeeded ( profileRequest , adaptor . getMetadataResolver ( ) , request , context ) ; }
Validate authn request signature .
18,253
protected void buildEntityCriteriaForSigningCredential ( final RequestAbstractType profileRequest , final CriteriaSet criteriaSet ) { criteriaSet . add ( new EntityIdCriterion ( SamlIdPUtils . getIssuerFromSamlObject ( profileRequest ) ) ) ; criteriaSet . add ( new EntityRoleCriterion ( SPSSODescriptor . DEFAULT_ELEMENT_NAME ) ) ; }
Build entity criteria for signing credential .
18,254
protected SignatureValidationConfiguration getSignatureValidationConfiguration ( ) { val config = DefaultSecurityConfigurationBootstrap . buildDefaultSignatureValidationConfiguration ( ) ; val samlIdp = casProperties . getAuthn ( ) . getSamlIdp ( ) ; if ( this . overrideBlackListedSignatureAlgorithms != null && ! samlIdp . getAlgs ( ) . getOverrideBlackListedSignatureSigningAlgorithms ( ) . isEmpty ( ) ) { config . setBlacklistedAlgorithms ( this . overrideBlackListedSignatureAlgorithms ) ; config . setWhitelistMerge ( true ) ; } if ( this . overrideWhiteListedAlgorithms != null && ! this . overrideWhiteListedAlgorithms . isEmpty ( ) ) { config . setWhitelistedAlgorithms ( this . overrideWhiteListedAlgorithms ) ; config . setBlacklistMerge ( true ) ; } LOGGER . debug ( "Signature validation blacklisted algorithms: [{}]" , config . getBlacklistedAlgorithms ( ) ) ; LOGGER . debug ( "Signature validation whitelisted algorithms: [{}]" , config . getWhitelistedAlgorithms ( ) ) ; return config ; }
Gets signature validation configuration .
18,255
protected TicketDefinition buildTicketDefinition ( final TicketCatalog plan , final String prefix , final Class impl , final int order ) { if ( plan . contains ( prefix ) ) { return plan . find ( prefix ) ; } return new DefaultTicketDefinition ( impl , prefix , order ) ; }
Build ticket ticket definition .
18,256
protected TicketDefinition buildTicketDefinition ( final TicketCatalog plan , final String prefix , final Class impl ) { if ( plan . contains ( prefix ) ) { return plan . find ( prefix ) ; } return new DefaultTicketDefinition ( impl , prefix , Ordered . LOWEST_PRECEDENCE ) ; }
Build ticket definition ticket .
18,257
protected String formatOutputMessageInternal ( final String message ) { try { return EncodingUtils . urlEncode ( message ) ; } catch ( final Exception e ) { LOGGER . warn ( "Unable to encode URL " + message , e ) ; } return message ; }
Encodes the message in UTF - 8 format in preparation to send .
18,258
protected static String cleanupUrl ( final String url ) { if ( url == null ) { return null ; } val jsessionPosition = url . indexOf ( ";jsession" ) ; if ( jsessionPosition == - 1 ) { return url ; } val questionMarkPosition = url . indexOf ( '?' ) ; if ( questionMarkPosition < jsessionPosition ) { return url . substring ( 0 , url . indexOf ( ";jsession" ) ) ; } return url . substring ( 0 , jsessionPosition ) + url . substring ( questionMarkPosition ) ; }
Cleanup the url . Removes jsession ids and query strings .
18,259
protected static String getSourceParameter ( final HttpServletRequest request , final String ... paramNames ) { if ( request != null ) { val parameterMap = request . getParameterMap ( ) ; return Stream . of ( paramNames ) . filter ( p -> parameterMap . containsKey ( p ) || request . getAttribute ( p ) != null ) . findFirst ( ) . orElse ( null ) ; } return null ; }
Gets source parameter .
18,260
public ResponseEntity handleWebFingerDiscoveryRequest ( final String resource , final String rel ) { if ( StringUtils . isNotBlank ( rel ) && ! OidcConstants . WEBFINGER_REL . equalsIgnoreCase ( rel ) ) { LOGGER . warn ( "Handling discovery request for a non-standard OIDC relation [{}]" , rel ) ; } val issuer = this . discovery . getIssuer ( ) ; if ( ! StringUtils . equalsIgnoreCase ( resource , issuer ) ) { val resourceUri = normalize ( resource ) ; if ( resourceUri == null ) { LOGGER . error ( "Unable to parse and normalize resource: [{}]" , resource ) ; return buildNotFoundResponseEntity ( "Unable to normalize provided resource" ) ; } val issuerUri = normalize ( issuer ) ; if ( issuerUri == null ) { LOGGER . error ( "Unable to parse and normalize issuer: [{}]" , issuer ) ; return buildNotFoundResponseEntity ( "Unable to normalize issuer" ) ; } if ( ! "acct" . equals ( resourceUri . getScheme ( ) ) ) { LOGGER . error ( "Unable to accept resource scheme: [{}]" , resourceUri . toUriString ( ) ) ; return buildNotFoundResponseEntity ( "Unable to recognize/accept resource scheme " + resourceUri . getScheme ( ) ) ; } var user = userInfoRepository . findByEmailAddress ( resourceUri . getUserInfo ( ) + '@' + resourceUri . getHost ( ) ) ; if ( user . isEmpty ( ) ) { user = userInfoRepository . findByUsername ( resourceUri . getUserInfo ( ) ) ; } if ( user . isEmpty ( ) ) { LOGGER . info ( "User/Resource not found: [{}]" , resource ) ; return buildNotFoundResponseEntity ( "Unable to find resource" ) ; } if ( ! StringUtils . equalsIgnoreCase ( issuerUri . getHost ( ) , resourceUri . getHost ( ) ) ) { LOGGER . info ( "Host mismatch for resource [{}]: expected [{}] and yet received [{}]" , resource , issuerUri . getHost ( ) , resourceUri . getHost ( ) ) ; return buildNotFoundResponseEntity ( "Unable to match resource host" ) ; } } val body = new LinkedHashMap < String , Object > ( ) ; body . put ( "subject" , resource ) ; val links = new ArrayList < > ( ) ; links . add ( CollectionUtils . wrap ( "rel" , OidcConstants . WEBFINGER_REL , "href" , issuer ) ) ; body . put ( "links" , links ) ; return new ResponseEntity < > ( body , HttpStatus . OK ) ; }
Handle web finger discovery request and produce response entity .
18,261
protected ResponseEntity buildNotFoundResponseEntity ( final String message ) { return new ResponseEntity < > ( CollectionUtils . wrap ( "message" , message ) , HttpStatus . NOT_FOUND ) ; }
Build not found response entity response entity .
18,262
protected UriComponents normalize ( final String resource ) { val builder = UriComponentsBuilder . newInstance ( ) ; val matcher = RESOURCE_NORMALIZED_PATTERN . matcher ( resource ) ; if ( ! matcher . matches ( ) ) { LOGGER . error ( "Unable to match the resource [{}] against pattern [{}] for normalization" , resource , matcher . pattern ( ) . pattern ( ) ) ; return null ; } builder . scheme ( matcher . group ( PATTERN_GROUP_INDEX_SCHEME ) ) ; builder . userInfo ( matcher . group ( PATTERN_GROUP_INDEX_USERINFO ) ) ; builder . host ( matcher . group ( PATTERN_GROUP_INDEX_HOST ) ) ; val port = matcher . group ( PATTERN_GROUP_INDEX_PORT ) ; if ( ! StringUtils . isBlank ( port ) ) { builder . port ( Integer . parseInt ( port ) ) ; } builder . path ( matcher . group ( PATTERN_GROUP_INDEX_PATH ) ) ; builder . query ( matcher . group ( PATTERN_GROUP_INDEX_QUERY ) ) ; builder . fragment ( matcher . group ( PATTERN_GROUP_INDEX_FRAGMENT ) ) ; val currentBuilder = builder . build ( ) ; if ( StringUtils . isBlank ( currentBuilder . getScheme ( ) ) ) { if ( ! StringUtils . isBlank ( currentBuilder . getUserInfo ( ) ) && StringUtils . isBlank ( currentBuilder . getPath ( ) ) && StringUtils . isBlank ( currentBuilder . getQuery ( ) ) && currentBuilder . getPort ( ) < 0 ) { builder . scheme ( "acct" ) ; } else { builder . scheme ( "https" ) ; } } builder . fragment ( null ) ; return builder . build ( ) ; }
Normalize uri components .
18,263
protected boolean isAccessTokenRequest ( final HttpServletRequest request , final HttpServletResponse response ) { val requestPath = request . getRequestURI ( ) ; val pattern = String . format ( "(%s|%s)" , OAuth20Constants . ACCESS_TOKEN_URL , OAuth20Constants . TOKEN_URL ) ; return doesUriMatchPattern ( requestPath , pattern ) ; }
Is access token request request .
18,264
protected boolean isDeviceTokenRequest ( final HttpServletRequest request , final HttpServletResponse response ) { val requestPath = request . getRequestURI ( ) ; val pattern = String . format ( "(%s)" , OAuth20Constants . DEVICE_AUTHZ_URL ) ; return doesUriMatchPattern ( requestPath , pattern ) ; }
Is device token request boolean .
18,265
protected boolean requestRequiresAuthentication ( final HttpServletRequest request , final HttpServletResponse response ) { val accessTokenRequest = isAccessTokenRequest ( request , response ) ; if ( ! accessTokenRequest ) { val extractor = extractAccessTokenGrantRequest ( request ) ; if ( extractor . isPresent ( ) ) { val ext = extractor . get ( ) ; return ext . requestMustBeAuthenticated ( ) ; } } else { val extractor = extractAccessTokenGrantRequest ( request ) ; if ( extractor . isPresent ( ) ) { val ext = extractor . get ( ) ; return ext . getResponseType ( ) != OAuth20ResponseTypes . DEVICE_CODE ; } } return false ; }
Request requires authentication .
18,266
protected boolean isAuthorizationRequest ( final HttpServletRequest request , final HttpServletResponse response ) { val requestPath = request . getRequestURI ( ) ; return doesUriMatchPattern ( requestPath , OAuth20Constants . AUTHORIZE_URL ) ; }
Is authorization request .
18,267
protected boolean doesUriMatchPattern ( final String requestPath , final String patternUrl ) { val pattern = Pattern . compile ( '/' + patternUrl + "(/)*$" ) ; return pattern . matcher ( requestPath ) . find ( ) ; }
Does uri match pattern .
18,268
protected static boolean isLogoutRequestConfirmed ( final RequestContext requestContext ) { val request = WebUtils . getHttpServletRequestFromExternalWebflowContext ( requestContext ) ; return request . getParameterMap ( ) . containsKey ( REQUEST_PARAM_LOGOUT_REQUEST_CONFIRMED ) ; }
Check if the logout must be confirmed .
18,269
protected void destroyApplicationSession ( final HttpServletRequest request , final HttpServletResponse response ) { LOGGER . trace ( "Destroying application session" ) ; val context = new J2EContext ( request , response , new J2ESessionStore ( ) ) ; val manager = new ProfileManager < > ( context , context . getSessionStore ( ) ) ; manager . logout ( ) ; val session = request . getSession ( false ) ; if ( session != null ) { val requestedUrl = session . getAttribute ( Pac4jConstants . REQUESTED_URL ) ; session . invalidate ( ) ; if ( requestedUrl != null && ! requestedUrl . equals ( StringUtils . EMPTY ) ) { request . getSession ( true ) . setAttribute ( Pac4jConstants . REQUESTED_URL , requestedUrl ) ; } } }
Destroy application session . Also kills all delegated authn profiles via pac4j .
18,270
protected boolean validateResourceSetScopes ( final ResourceSet rs ) { if ( rs . getPolicies ( ) == null || rs . getPolicies ( ) . isEmpty ( ) ) { return true ; } return rs . getPolicies ( ) . stream ( ) . flatMap ( policy -> policy . getPermissions ( ) . stream ( ) ) . allMatch ( permission -> rs . getScopes ( ) . containsAll ( permission . getScopes ( ) ) ) ; }
Validate resource set scopes .
18,271
private String collectEnvironmentInfo ( final Environment environment , final Class < ? > sourceClass ) { val properties = System . getProperties ( ) ; if ( properties . containsKey ( "CAS_BANNER_SKIP" ) ) { try ( val formatter = new Formatter ( ) ) { formatter . format ( "CAS Version: %s%n" , CasVersion . getVersion ( ) ) ; return formatter . toString ( ) ; } } try ( val formatter = new Formatter ( ) ) { val sysInfo = SystemUtils . getSystemInfo ( ) ; sysInfo . forEach ( ( k , v ) -> { if ( k . startsWith ( SEPARATOR_CHAR ) ) { formatter . format ( "%s%n" , LINE_SEPARATOR ) ; } else { formatter . format ( "%s: %s%n" , k , v ) ; } } ) ; formatter . format ( "%s%n" , LINE_SEPARATOR ) ; injectEnvironmentInfoIntoBanner ( formatter , environment , sourceClass ) ; return formatter . toString ( ) ; } }
Collect environment info with details on the java and os deployment versions .
18,272
protected boolean shouldSignTokenFor ( final OidcRegisteredService svc ) { if ( AlgorithmIdentifiers . NONE . equalsIgnoreCase ( svc . getIdTokenSigningAlg ( ) ) ) { LOGGER . warn ( "ID token signing algorithm is set to none for [{}] and ID token will not be signed" , svc . getServiceId ( ) ) ; return false ; } return svc . isSignIdToken ( ) ; }
Should sign token for service?
18,273
protected boolean shouldEncryptTokenFor ( final OidcRegisteredService svc ) { if ( AlgorithmIdentifiers . NONE . equalsIgnoreCase ( svc . getIdTokenEncryptionAlg ( ) ) ) { LOGGER . warn ( "ID token encryption algorithm is set to none for [{}] and ID token will not be encrypted" , svc . getServiceId ( ) ) ; return false ; } return svc . isEncryptIdToken ( ) && StringUtils . isNotBlank ( svc . getIdTokenEncryptionAlg ( ) ) && StringUtils . isNotBlank ( svc . getIdTokenEncryptionEncoding ( ) ) ; }
Should encrypt token for service?
18,274
@ PostMapping ( path = SamlIdPConstants . ENDPOINT_SAML2_SLO_PROFILE_POST ) protected void handleSaml2ProfileSLOPostRequest ( final HttpServletResponse response , final HttpServletRequest request ) throws Exception { val decoder = getSamlProfileHandlerConfigurationContext ( ) . getSamlMessageDecoders ( ) . get ( HttpMethod . POST ) ; handleSloProfileRequest ( response , request , decoder ) ; }
Handle SLO POST profile request .
18,275
public static CloudWatchAppender createAppender ( @ PluginAttribute ( "name" ) final String name , @ PluginAttribute ( "awsLogStreamName" ) final String awsLogStreamName , @ PluginAttribute ( "awsLogGroupName" ) final String awsLogGroupName , @ PluginAttribute ( "awsLogStreamFlushPeriodInSeconds" ) final String awsLogStreamFlushPeriodInSeconds , @ PluginAttribute ( "credentialAccessKey" ) final String credentialAccessKey , @ PluginAttribute ( "credentialSecretKey" ) final String credentialSecretKey , @ PluginAttribute ( "awsLogRegionName" ) final String awsLogRegionName , @ PluginElement ( "Layout" ) final Layout < Serializable > layout ) { return new CloudWatchAppender ( name , awsLogGroupName , awsLogStreamName , awsLogStreamFlushPeriodInSeconds , StringUtils . defaultIfBlank ( credentialAccessKey , System . getProperty ( "AWS_ACCESS_KEY" ) ) , StringUtils . defaultIfBlank ( credentialSecretKey , System . getProperty ( "AWS_SECRET_KEY" ) ) , StringUtils . defaultIfBlank ( awsLogRegionName , System . getProperty ( "AWS_REGION_NAME" ) ) , layout ) ; }
Create appender cloud watch appender .
18,276
@ ShellMethod ( key = "add-properties" , value = "Add properties associated with a CAS group/module to a Properties/Yaml configuration file." ) public static void add ( @ ShellOption ( value = { "file" } , help = "Path to the CAS configuration file" , defaultValue = "/etc/cas/config/cas.properties" ) final String file , @ ShellOption ( value = { "group" } , help = "Group/module whose associated settings should be added to the CAS configuration file" ) final String group ) throws Exception { if ( StringUtils . isBlank ( file ) ) { LOGGER . warn ( "Configuration file must be specified" ) ; return ; } val filePath = new File ( file ) ; if ( filePath . exists ( ) && ( filePath . isDirectory ( ) || ! filePath . canRead ( ) || ! filePath . canWrite ( ) ) ) { LOGGER . warn ( "Configuration file [{}] is not readable/writable or is not a path to a file" , filePath . getCanonicalPath ( ) ) ; return ; } val results = findProperties ( group ) ; LOGGER . info ( "Located [{}] properties matching [{}]" , results . size ( ) , group ) ; switch ( FilenameUtils . getExtension ( filePath . getName ( ) ) . toLowerCase ( ) ) { case "properties" : createConfigurationFileIfNeeded ( filePath ) ; val props = loadPropertiesFromConfigurationFile ( filePath ) ; writeConfigurationPropertiesToFile ( filePath , results , props ) ; break ; case "yml" : createConfigurationFileIfNeeded ( filePath ) ; val yamlProps = CasCoreConfigurationUtils . loadYamlProperties ( new FileSystemResource ( filePath ) ) ; writeYamlConfigurationPropertiesToFile ( filePath , results , yamlProps ) ; break ; default : LOGGER . warn ( "Configuration file format [{}] is not recognized" , filePath . getCanonicalPath ( ) ) ; } }
Add properties to configuration .
18,277
public static String getPropertyGroupId ( final ConfigurationMetadataProperty prop ) { if ( isCasProperty ( prop ) ) { return StringUtils . substringBeforeLast ( prop . getName ( ) , "." ) ; } return StringUtils . substringBeforeLast ( prop . getId ( ) , "." ) ; }
Gets property group id .
18,278
protected JwtClaims buildJwtClaims ( final HttpServletRequest request , final AccessToken accessTokenId , final long timeoutInSeconds , final OAuthRegisteredService service , final UserProfile profile , final J2EContext context , final OAuth20ResponseTypes responseType ) { val permissionTicket = ( UmaPermissionTicket ) request . getAttribute ( UmaPermissionTicket . class . getName ( ) ) ; val claims = new JwtClaims ( ) ; claims . setJwtId ( UUID . randomUUID ( ) . toString ( ) ) ; claims . setIssuer ( getConfigurationContext ( ) . getCasProperties ( ) . getAuthn ( ) . getUma ( ) . getIssuer ( ) ) ; claims . setAudience ( String . valueOf ( permissionTicket . getResourceSet ( ) . getId ( ) ) ) ; val expirationDate = NumericDate . now ( ) ; expirationDate . addSeconds ( timeoutInSeconds ) ; claims . setExpirationTime ( expirationDate ) ; claims . setIssuedAtToNow ( ) ; claims . setSubject ( profile . getId ( ) ) ; permissionTicket . getClaims ( ) . forEach ( ( k , v ) -> claims . setStringListClaim ( k , v . toString ( ) ) ) ; claims . setStringListClaim ( OAuth20Constants . SCOPE , new ArrayList < > ( permissionTicket . getScopes ( ) ) ) ; claims . setStringListClaim ( OAuth20Constants . CLIENT_ID , service . getClientId ( ) ) ; return claims ; }
Build jwt claims jwt claims .
18,279
private Optional < JsonWebKeySet > buildJsonWebKeySet ( ) { try { LOGGER . debug ( "Loading default JSON web key from [{}]" , this . jwksFile ) ; if ( this . jwksFile != null ) { LOGGER . debug ( "Retrieving default JSON web key from [{}]" , this . jwksFile ) ; val jsonWebKeySet = buildJsonWebKeySet ( this . jwksFile ) ; if ( jsonWebKeySet == null || jsonWebKeySet . getJsonWebKeys ( ) . isEmpty ( ) ) { LOGGER . warn ( "No JSON web keys could be found" ) ; return Optional . empty ( ) ; } val badKeysCount = jsonWebKeySet . getJsonWebKeys ( ) . stream ( ) . filter ( k -> StringUtils . isBlank ( k . getAlgorithm ( ) ) && StringUtils . isBlank ( k . getKeyId ( ) ) && StringUtils . isBlank ( k . getKeyType ( ) ) ) . count ( ) ; if ( badKeysCount == jsonWebKeySet . getJsonWebKeys ( ) . size ( ) ) { LOGGER . warn ( "No valid JSON web keys could be found" ) ; return Optional . empty ( ) ; } val webKey = getJsonSigningWebKeyFromJwks ( jsonWebKeySet ) ; if ( webKey . getPrivateKey ( ) == null ) { LOGGER . warn ( "JSON web key retrieved [{}] has no associated private key" , webKey . getKeyId ( ) ) ; return Optional . empty ( ) ; } return Optional . of ( jsonWebKeySet ) ; } } catch ( final Exception e ) { LOGGER . debug ( e . getMessage ( ) , e ) ; } return Optional . empty ( ) ; }
Build json web key set .
18,280
public Map < String , String > getAssociationResponse ( final HttpServletRequest request ) { val parameters = new ParameterList ( request . getParameterMap ( ) ) ; val mode = parameters . hasParameter ( OpenIdProtocolConstants . OPENID_MODE ) ? parameters . getParameterValue ( OpenIdProtocolConstants . OPENID_MODE ) : null ; val response = FunctionUtils . doIf ( StringUtils . equals ( mode , OpenIdProtocolConstants . ASSOCIATE ) , ( ) -> this . serverManager . associationResponse ( parameters ) , ( ) -> null ) . get ( ) ; val responseParams = new HashMap < String , String > ( ) ; if ( response != null ) { responseParams . putAll ( response . getParameterMap ( ) ) ; } return responseParams ; }
Gets the association response . Determines the mode first . If mode is set to associate will set the response . Then builds the response parameters next and returns .
18,281
public boolean canPing ( ) { val uidPsw = getClass ( ) . getSimpleName ( ) ; for ( val server : this . servers ) { LOGGER . debug ( "Attempting to ping RADIUS server [{}] via simulating an authentication request. If the server responds " + "successfully, mock authentication will fail correctly." , server ) ; try { server . authenticate ( uidPsw , uidPsw ) ; } catch ( final TimeoutException | SocketTimeoutException e ) { LOGGER . debug ( "Server [{}] is not available" , server ) ; continue ; } catch ( final Exception e ) { LOGGER . debug ( "Pinging RADIUS server was successful. Response [{}]" , e . getMessage ( ) ) ; } return true ; } return false ; }
Can ping .
18,282
public static void render ( final Object model , final HttpServletResponse response ) { val jsonConverter = new MappingJackson2HttpMessageConverter ( ) ; jsonConverter . setPrettyPrint ( true ) ; val jsonMimeType = MediaType . APPLICATION_JSON ; jsonConverter . write ( model , jsonMimeType , new ServletServerHttpResponse ( response ) ) ; }
Render model and view .
18,283
public static void render ( final HttpServletResponse response ) { val map = new HashMap < String , Object > ( ) ; response . setStatus ( HttpServletResponse . SC_OK ) ; render ( map , response ) ; }
Render model and view . Sets the response status to OK .
18,284
public static void renderException ( final Exception ex , final HttpServletResponse response ) { val map = new HashMap < String , String > ( ) ; map . put ( "error" , ex . getMessage ( ) ) ; map . put ( "stacktrace" , Arrays . deepToString ( ex . getStackTrace ( ) ) ) ; renderException ( map , response ) ; }
Render exceptions . Adds error messages and the stack trace to the json model and sets the response status accordingly to note bad requests .
18,285
private static void renderException ( final Map model , final HttpServletResponse response ) { response . setStatus ( HttpServletResponse . SC_BAD_REQUEST ) ; model . put ( "status" , HttpServletResponse . SC_BAD_REQUEST ) ; render ( model , response ) ; }
Render exceptions . Sets the response status accordingly to note bad requests .
18,286
public ResponseEntity < SimplePrincipal > authenticate ( final UsernamePasswordCredential c ) { val entity = new HttpEntity < Object > ( HttpUtils . createBasicAuthHeaders ( c . getUsername ( ) , c . getPassword ( ) ) ) ; return restTemplate . exchange ( authenticationUri , HttpMethod . POST , entity , SimplePrincipal . class ) ; }
Authenticate and receive entity from the rest template .
18,287
protected AuthenticationRiskContingencyResponse executeInternal ( final Authentication authentication , final RegisteredService service , final AuthenticationRiskScore score , final HttpServletRequest request ) { return null ; }
Execute authentication risk contingency plan .
18,288
public DefaultTicketFactory addTicketFactory ( final Class < ? extends Ticket > ticketClass , final TicketFactory factory ) { this . factoryMap . put ( ticketClass . getCanonicalName ( ) , factory ) ; return this ; }
Add ticket factory .
18,289
public void run ( ) { try { LOGGER . debug ( "Attempting to resolve [{}]" , this . ipAddress ) ; val address = InetAddress . getByName ( this . ipAddress ) ; set ( address . getCanonicalHostName ( ) ) ; } catch ( final UnknownHostException e ) { LOGGER . debug ( "Unable to identify the canonical hostname for ip address." , e ) ; } }
Runnable implementation to thread the work done in this class allowing the implementer to set a thread timeout and thereby short - circuit the lookup .
18,290
protected Response buildSaml2Response ( final Object casAssertion , final RequestAbstractType authnRequest , final SamlRegisteredService service , final SamlRegisteredServiceServiceProviderMetadataFacade adaptor , final HttpServletRequest request , final String binding , final MessageContext messageContext ) { return ( Response ) getSamlResponseBuilderConfigurationContext ( ) . getSamlSoapResponseBuilder ( ) . build ( authnRequest , request , null , casAssertion , service , adaptor , binding , messageContext ) ; }
Build saml2 response .
18,291
protected SecurityToken getSecurityTokenFromRequest ( final HttpServletRequest request ) { val cookieValue = wsFederationRequestConfigurationContext . getTicketGrantingTicketCookieGenerator ( ) . retrieveCookieValue ( request ) ; if ( StringUtils . isNotBlank ( cookieValue ) ) { val tgt = wsFederationRequestConfigurationContext . getTicketRegistry ( ) . getTicket ( cookieValue , TicketGrantingTicket . class ) ; if ( tgt != null ) { val sts = tgt . getDescendantTickets ( ) . stream ( ) . filter ( t -> t . startsWith ( SecurityTokenTicket . PREFIX ) ) . findFirst ( ) . orElse ( null ) ; if ( StringUtils . isNotBlank ( sts ) ) { val stt = wsFederationRequestConfigurationContext . getTicketRegistry ( ) . getTicket ( sts , SecurityTokenTicket . class ) ; if ( stt == null || stt . isExpired ( ) ) { LOGGER . warn ( "Security token ticket [{}] is not found or has expired" , sts ) ; return null ; } if ( stt . getSecurityToken ( ) . isExpired ( ) ) { LOGGER . warn ( "Security token linked to ticket [{}] has expired" , sts ) ; return null ; } return stt . getSecurityToken ( ) ; } } } return null ; }
Gets security token from request .
18,292
protected boolean shouldRenewAuthentication ( final WSFederationRequest fedRequest , final HttpServletRequest request ) { if ( StringUtils . isBlank ( fedRequest . getWfresh ( ) ) || NumberUtils . isCreatable ( fedRequest . getWfresh ( ) ) ) { return false ; } val ttl = Long . parseLong ( fedRequest . getWfresh ( ) . trim ( ) ) ; if ( ttl == 0 ) { return false ; } val idpToken = getSecurityTokenFromRequest ( request ) ; if ( idpToken == null ) { return true ; } val ttlMs = TimeUnit . MINUTES . toMillis ( ttl ) ; if ( ttlMs > 0 ) { val createdDate = idpToken . getCreated ( ) ; if ( createdDate != null ) { val expiryDate = new Date ( ) ; expiryDate . setTime ( createdDate . toEpochMilli ( ) + ttlMs ) ; return expiryDate . before ( new Date ( ) ) ; } } return false ; }
Is authentication required?
18,293
@ ExceptionHandler ( Exception . class ) public ModelAndView handleUnauthorizedServiceException ( final HttpServletRequest req , final Exception ex ) { return WebUtils . produceUnauthorizedErrorView ( ) ; }
Handle unauthorized service exception .
18,294
public static < T , R > Function < T , R > doIf ( final Predicate < T > condition , final CheckedFunction < T , R > trueFunction , final CheckedFunction < T , R > falseFunction ) { return t -> { try { if ( condition . test ( t ) ) { return trueFunction . apply ( t ) ; } return falseFunction . apply ( t ) ; } catch ( final Throwable e ) { LOGGER . warn ( e . getMessage ( ) , e ) ; try { return falseFunction . apply ( t ) ; } catch ( final Throwable ex ) { throw new IllegalArgumentException ( ex . getMessage ( ) ) ; } } } ; }
Conditional function function .
18,295
public static < R > Supplier < R > doIfNotNull ( final Object input , final Supplier < R > trueFunction , final Supplier < R > falseFunction ) { return ( ) -> { try { if ( input != null ) { return trueFunction . get ( ) ; } return falseFunction . get ( ) ; } catch ( final Throwable e ) { LOGGER . warn ( e . getMessage ( ) , e ) ; return falseFunction . get ( ) ; } } ; }
Supply if not null supplier .
18,296
public static < T > void doIfNotNull ( final T input , final Consumer < T > trueFunction ) { try { if ( input != null ) { trueFunction . accept ( input ) ; } } catch ( final Throwable e ) { LOGGER . warn ( e . getMessage ( ) , e ) ; } }
Do if not null .
18,297
public static < T , R > Function < T , R > doAndHandle ( final CheckedFunction < T , R > function , final CheckedFunction < Throwable , R > errorHandler ) { return t -> { try { return function . apply ( t ) ; } catch ( final Throwable e ) { LOGGER . warn ( e . getMessage ( ) , e ) ; try { return errorHandler . apply ( e ) ; } catch ( final Throwable ex ) { throw new IllegalArgumentException ( ex . getMessage ( ) ) ; } } } ; }
Default function function .
18,298
public static < R > Supplier < R > doAndHandle ( final Supplier < R > function , final CheckedFunction < Throwable , R > errorHandler ) { return ( ) -> { try { return function . get ( ) ; } catch ( final Throwable e ) { LOGGER . warn ( e . getMessage ( ) , e ) ; try { return errorHandler . apply ( e ) ; } catch ( final Throwable ex ) { throw new IllegalArgumentException ( ex . getMessage ( ) ) ; } } } ; }
Do and handle supplier .
18,299
public String build ( final JwtRequest payload ) { val serviceAudience = payload . getServiceAudience ( ) ; val claims = new JWTClaimsSet . Builder ( ) . audience ( serviceAudience ) . issuer ( casSeverPrefix ) . jwtID ( payload . getJwtId ( ) ) . issueTime ( payload . getIssueDate ( ) ) . subject ( payload . getSubject ( ) ) ; payload . getAttributes ( ) . forEach ( claims :: claim ) ; claims . expirationTime ( payload . getValidUntilDate ( ) ) ; val claimsSet = claims . build ( ) ; val object = claimsSet . toJSONObject ( ) ; val jwtJson = object . toJSONString ( ) ; LOGGER . debug ( "Generated JWT [{}]" , JsonValue . readJSON ( jwtJson ) . toString ( Stringify . FORMATTED ) ) ; LOGGER . trace ( "Locating service [{}] in service registry" , serviceAudience ) ; val registeredService = this . servicesManager . findServiceBy ( serviceAudience ) ; RegisteredServiceAccessStrategyUtils . ensureServiceAccessIsAllowed ( registeredService ) ; LOGGER . trace ( "Locating service specific signing and encryption keys for [{}] in service registry" , serviceAudience ) ; if ( registeredServiceCipherExecutor . supports ( registeredService ) ) { LOGGER . trace ( "Encoding JWT based on keys provided by service [{}]" , registeredService . getServiceId ( ) ) ; return registeredServiceCipherExecutor . encode ( jwtJson , Optional . of ( registeredService ) ) ; } if ( defaultTokenCipherExecutor . isEnabled ( ) ) { LOGGER . trace ( "Encoding JWT based on default global keys for [{}]" , serviceAudience ) ; return defaultTokenCipherExecutor . encode ( jwtJson ) ; } val header = new PlainHeader . Builder ( ) . type ( JOSEObjectType . JWT ) . build ( ) ; val token = new PlainJWT ( header , claimsSet ) . serialize ( ) ; LOGGER . trace ( "Generating plain JWT as the ticket: [{}]" , token ) ; return token ; }
Build JWT .