idx
int64
0
41.2k
question
stringlengths
74
4.21k
target
stringlengths
5
888
25,200
public void xmlns ( Map < String , String > definition ) { Assert . notNull ( namespaceHandlerResolver , "You cannot define a Spring namespace without a [namespaceHandlerResolver] set" ) ; if ( definition . isEmpty ( ) ) { return ; } for ( Map . Entry < String , String > entry : definition . entrySet ( ) ) { String namespace = entry . getKey ( ) ; String uri = entry . getValue ( ) == null ? null : entry . getValue ( ) ; Assert . notNull ( uri , "Namespace definition cannot supply a null URI" ) ; final NamespaceHandler namespaceHandler = namespaceHandlerResolver . resolve ( uri ) ; if ( namespaceHandler == null ) { throw new BeanDefinitionParsingException ( new Problem ( "No namespace handler found for URI: " + uri , new Location ( readerContext . getResource ( ) ) ) ) ; } namespaceHandlers . put ( namespace , namespaceHandler ) ; namespaces . put ( namespace , uri ) ; } }
Defines a Spring namespace definition to use .
25,201
public void registerBeans ( BeanDefinitionRegistry registry ) { finalizeDeferredProperties ( ) ; if ( registry instanceof GenericApplicationContext ) { GenericApplicationContext ctx = ( GenericApplicationContext ) registry ; ctx . setClassLoader ( classLoader ) ; ctx . getBeanFactory ( ) . setBeanClassLoader ( classLoader ) ; } springConfig . registerBeansWithRegistry ( registry ) ; }
Register a set of beans with the given bean registry . Most application contexts are bean registries .
25,202
public Object invokeMethod ( String name , Object arg ) { Object [ ] args = ( Object [ ] ) arg ; if ( CREATE_APPCTX . equals ( name ) ) { return createApplicationContext ( ) ; } if ( REGISTER_BEANS . equals ( name ) && args . length == 1 && args [ 0 ] instanceof GenericApplicationContext ) { registerBeans ( ( GenericApplicationContext ) args [ 0 ] ) ; return null ; } if ( BEANS . equals ( name ) && args . length == 1 && args [ 0 ] instanceof Closure ) { return beans ( ( Closure < ? > ) args [ 0 ] ) ; } if ( REF . equals ( name ) ) { String refName ; Assert . notNull ( args [ 0 ] , "Argument to ref() is not a valid bean or was not found" ) ; if ( args [ 0 ] instanceof RuntimeBeanReference ) { refName = ( ( RuntimeBeanReference ) args [ 0 ] ) . getBeanName ( ) ; } else { refName = args [ 0 ] . toString ( ) ; } boolean parentRef = false ; if ( args . length > 1 ) { if ( args [ 1 ] instanceof Boolean ) { parentRef = ( Boolean ) args [ 1 ] ; } } return new RuntimeBeanReference ( refName , parentRef ) ; } if ( namespaceHandlers . containsKey ( name ) && args . length > 0 && ( args [ 0 ] instanceof Closure ) ) { createDynamicElementReader ( name , true ) . invokeMethod ( "doCall" , args ) ; return this ; } if ( args . length > 0 && args [ 0 ] instanceof Closure ) { return invokeBeanDefiningMethod ( name , args ) ; } if ( args . length > 0 && args [ 0 ] instanceof Class || args . length > 0 && args [ 0 ] instanceof RuntimeBeanReference || args . length > 0 && args [ 0 ] instanceof Map ) { return invokeBeanDefiningMethod ( name , args ) ; } if ( args . length > 1 && args [ args . length - 1 ] instanceof Closure ) { return invokeBeanDefiningMethod ( name , args ) ; } ApplicationContext ctx = springConfig . getUnrefreshedApplicationContext ( ) ; MetaClass mc = DefaultGroovyMethods . getMetaClass ( ctx ) ; if ( ! mc . respondsTo ( ctx , name , args ) . isEmpty ( ) ) { return mc . invokeMethod ( ctx , name , args ) ; } return this ; }
Overrides method invocation to create beans for each method name that takes a class argument .
25,203
public void setProperty ( String name , Object value ) { if ( currentBeanConfig != null ) { setPropertyOnBeanConfig ( name , value ) ; } }
Overrides property setting in the scope of the BeanBuilder to set properties on the current BeanConfiguration .
25,204
@ SuppressWarnings ( "rawtypes" ) public AbstractBeanDefinition bean ( Class type , Object ... args ) { BeanConfiguration current = currentBeanConfig ; try { Closure callable = null ; Collection constructorArgs = null ; if ( args != null && args . length > 0 ) { int index = args . length ; Object lastArg = args [ index - 1 ] ; if ( lastArg instanceof Closure ) { callable = ( Closure ) lastArg ; index -- ; } if ( index > - 1 ) { constructorArgs = resolveConstructorArguments ( args , 0 , index ) ; } } currentBeanConfig = constructorArgs == null ? springConfig . createSingletonBean ( type ) : springConfig . createSingletonBean ( type , constructorArgs ) ; if ( callable != null ) { callable . call ( new Object [ ] { currentBeanConfig } ) ; } return currentBeanConfig . getBeanDefinition ( ) ; } finally { currentBeanConfig = current ; } }
Defines an inner bean definition .
25,205
@ SuppressWarnings ( { "rawtypes" , "unchecked" } ) protected Object manageMapIfNecessary ( Object value ) { Map map = ( Map ) value ; boolean containsRuntimeRefs = false ; for ( Object e : map . values ( ) ) { if ( e instanceof RuntimeBeanReference ) { containsRuntimeRefs = true ; break ; } } if ( containsRuntimeRefs ) { Map managedMap = new ManagedMap ( ) ; managedMap . putAll ( map ) ; return managedMap ; } return value ; }
Checks whether there are any runtime refs inside a Map and converts it to a ManagedMap if necessary .
25,206
@ SuppressWarnings ( { "rawtypes" , "unchecked" } ) protected Object manageListIfNecessary ( Object value ) { List list = ( List ) value ; boolean containsRuntimeRefs = false ; for ( Object e : list ) { if ( e instanceof RuntimeBeanReference ) { containsRuntimeRefs = true ; break ; } } if ( containsRuntimeRefs ) { List tmp = new ManagedList ( ) ; tmp . addAll ( ( List ) value ) ; value = tmp ; } return value ; }
Checks whether there are any runtime refs inside the list and converts it to a ManagedList if necessary .
25,207
private void loadDelayedPlugins ( ) { while ( ! delayedLoadPlugins . isEmpty ( ) ) { GrailsPlugin plugin = delayedLoadPlugins . remove ( 0 ) ; if ( areDependenciesResolved ( plugin ) ) { if ( ! hasValidPluginsToLoadBefore ( plugin ) ) { registerPlugin ( plugin ) ; } else { delayedLoadPlugins . add ( plugin ) ; } } else { boolean foundInDelayed = false ; for ( GrailsPlugin remainingPlugin : delayedLoadPlugins ) { if ( isDependentOn ( plugin , remainingPlugin ) ) { foundInDelayed = true ; break ; } } if ( foundInDelayed ) { delayedLoadPlugins . add ( plugin ) ; } else { failedPlugins . put ( plugin . getName ( ) , plugin ) ; LOG . error ( "ERROR: Plugin [" + plugin . getName ( ) + "] cannot be loaded because its dependencies [" + DefaultGroovyMethods . inspect ( plugin . getDependencyNames ( ) ) + "] cannot be resolved" ) ; } } } }
This method will attempt to load that plug - ins not loaded in the first pass
25,208
private boolean isDependentOn ( GrailsPlugin plugin , GrailsPlugin dependency ) { for ( String name : plugin . getDependencyNames ( ) ) { String requiredVersion = plugin . getDependentVersion ( name ) ; if ( name . equals ( dependency . getName ( ) ) && GrailsVersionUtils . isValidVersion ( dependency . getVersion ( ) , requiredVersion ) ) return true ; } return false ; }
Checks whether the first plugin is dependant on the second plugin .
25,209
private boolean areNoneToLoadBefore ( GrailsPlugin plugin ) { for ( String name : plugin . getLoadAfterNames ( ) ) { if ( getGrailsPlugin ( name ) == null ) { return false ; } } return true ; }
Returns true if there are no plugins left that should if possible be loaded before this plugin .
25,210
private void attemptPluginLoad ( GrailsPlugin plugin ) { if ( areDependenciesResolved ( plugin ) && areNoneToLoadBefore ( plugin ) ) { registerPlugin ( plugin ) ; } else { delayedLoadPlugins . add ( plugin ) ; } }
Attempts to load a plugin based on its dependencies . If a plugin s dependencies cannot be resolved it will add it to the list of dependencies to be resolved later .
25,211
public Date getDate ( String name ) { Object returnValue = wrappedMap . get ( name ) ; if ( "date.struct" . equals ( returnValue ) ) { returnValue = lazyEvaluateDateParam ( name ) ; nestedDateMap . put ( name , returnValue ) ; return ( Date ) returnValue ; } Date date = super . getDate ( name ) ; if ( date == null ) { String format = lookupFormat ( name ) ; if ( format != null ) { return getDate ( name , format ) ; } } return date ; }
Obtains a date for the parameter name using the default format
25,212
public String toQueryString ( ) { String encoding = request . getCharacterEncoding ( ) ; try { return WebUtils . toQueryString ( this , encoding ) ; } catch ( UnsupportedEncodingException e ) { throw new ControllerExecutionException ( "Unable to convert parameter map [" + this + "] to a query string: " + e . getMessage ( ) , e ) ; } }
Converts this parameter map into a query String . Note that this will flatten nested keys separating them with the . character and URL encode the result
25,213
protected void validateLogoutRequest ( final LogoutRequest logoutRequest , final SAML2MessageContext context , final SignatureTrustEngine engine ) { validateSignatureIfItExists ( logoutRequest . getSignature ( ) , context , engine ) ; validateIssuerIfItExists ( logoutRequest . getIssuer ( ) , context ) ; NameID nameId = logoutRequest . getNameID ( ) ; final EncryptedID encryptedID = logoutRequest . getEncryptedID ( ) ; if ( encryptedID != null ) { nameId = decryptEncryptedId ( encryptedID , decrypter ) ; } String sessionIndex = null ; final List < SessionIndex > sessionIndexes = logoutRequest . getSessionIndexes ( ) ; if ( sessionIndexes != null && ! sessionIndexes . isEmpty ( ) ) { final SessionIndex sessionIndexObject = sessionIndexes . get ( 0 ) ; if ( sessionIndexObject != null ) { sessionIndex = sessionIndexObject . getSessionIndex ( ) ; } } final String sloKey = computeSloKey ( sessionIndex , nameId ) ; if ( sloKey != null ) { final String bindingUri = context . getSAMLBindingContext ( ) . getBindingUri ( ) ; if ( SAMLConstants . SAML2_SOAP11_BINDING_URI . equals ( bindingUri ) ) { logoutHandler . destroySessionBack ( context . getWebContext ( ) , sloKey ) ; } else { logoutHandler . destroySessionFront ( context . getWebContext ( ) , sloKey ) ; } } }
Validates the SAML logout request .
25,214
protected void validateLogoutResponse ( final LogoutResponse logoutResponse , final SAML2MessageContext context , final SignatureTrustEngine engine ) { validateSuccess ( logoutResponse . getStatus ( ) ) ; validateSignatureIfItExists ( logoutResponse . getSignature ( ) , context , engine ) ; validateIssueInstant ( logoutResponse . getIssueInstant ( ) ) ; validateIssuerIfItExists ( logoutResponse . getIssuer ( ) , context ) ; verifyEndpoint ( context . getSPSSODescriptor ( ) . getSingleLogoutServices ( ) . get ( 0 ) , logoutResponse . getDestination ( ) ) ; }
Validates the SAML logout response .
25,215
public static boolean isGet ( final WebContext context ) { return HttpConstants . HTTP_METHOD . GET . name ( ) . equalsIgnoreCase ( context . getRequestMethod ( ) ) ; }
Whether it is a GET request .
25,216
public static boolean isPost ( final WebContext context ) { return HttpConstants . HTTP_METHOD . POST . name ( ) . equalsIgnoreCase ( context . getRequestMethod ( ) ) ; }
Whether it is a POST request .
25,217
public static boolean isPut ( final WebContext context ) { return HttpConstants . HTTP_METHOD . PUT . name ( ) . equalsIgnoreCase ( context . getRequestMethod ( ) ) ; }
Whether it is a PUT request .
25,218
public static boolean isPatch ( final WebContext context ) { return HttpConstants . HTTP_METHOD . PATCH . name ( ) . equalsIgnoreCase ( context . getRequestMethod ( ) ) ; }
Whether it is a PATCH request .
25,219
public static boolean isDelete ( final WebContext context ) { return HttpConstants . HTTP_METHOD . DELETE . name ( ) . equalsIgnoreCase ( context . getRequestMethod ( ) ) ; }
Whether it is a DELETE request .
25,220
protected final void validateSuccess ( final Status status ) { String statusValue = status . getStatusCode ( ) . getValue ( ) ; if ( ! StatusCode . SUCCESS . equals ( statusValue ) ) { final StatusMessage statusMessage = status . getStatusMessage ( ) ; if ( statusMessage != null ) { statusValue += " / " + statusMessage . getMessage ( ) ; } throw new SAMLException ( "Response is not success ; actual " + statusValue ) ; } }
Validates that the response is a success .
25,221
protected final void validateSignature ( final Signature signature , final String idpEntityId , final SignatureTrustEngine trustEngine ) { final SAMLSignatureProfileValidator validator = new SAMLSignatureProfileValidator ( ) ; try { validator . validate ( signature ) ; } catch ( final SignatureException e ) { throw new SAMLSignatureValidationException ( "SAMLSignatureProfileValidator failed to validate signature" , e ) ; } final CriteriaSet 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 ( idpEntityId ) ) ; final boolean valid ; try { valid = trustEngine . validate ( signature , criteriaSet ) ; } catch ( final SecurityException e ) { throw new SAMLSignatureValidationException ( "An error occurred during signature validation" , e ) ; } if ( ! valid ) { throw new SAMLSignatureValidationException ( "Signature is not trusted" ) ; } }
Validate the given digital signature by checking its profile and value .
25,222
protected final void validateIssuer ( final Issuer issuer , final SAML2MessageContext context ) { if ( issuer . getFormat ( ) != null && ! issuer . getFormat ( ) . equals ( NameIDType . ENTITY ) ) { throw new SAMLIssuerException ( "Issuer type is not entity but " + issuer . getFormat ( ) ) ; } final String entityId = context . getSAMLPeerEntityContext ( ) . getEntityId ( ) ; if ( entityId == null || ! entityId . equals ( issuer . getValue ( ) ) ) { throw new SAMLIssuerException ( "Issuer " + issuer . getValue ( ) + " does not match idp entityId " + entityId ) ; } }
Validate issuer format and value .
25,223
protected final NameID decryptEncryptedId ( final EncryptedID encryptedId , final Decrypter decrypter ) throws SAMLException { if ( encryptedId == null ) { return null ; } if ( decrypter == null ) { logger . warn ( "Encrypted attributes returned, but no keystore was provided." ) ; return null ; } try { final NameID decryptedId = ( NameID ) decrypter . decrypt ( encryptedId ) ; return decryptedId ; } catch ( final DecryptionException e ) { throw new SAMLNameIdDecryptionException ( "Decryption of an EncryptedID failed." , e ) ; } }
Decrypts an EncryptedID using a decrypter .
25,224
protected void populateVelocityContext ( VelocityContext velocityContext , MessageContext < SAMLObject > messageContext , String endpointURL ) throws MessageEncodingException { String encodedEndpointURL = HTMLEncoder . encodeForHTMLAttribute ( endpointURL ) ; log . debug ( "Encoding action url of '{}' with encoded value '{}'" , endpointURL , encodedEndpointURL ) ; velocityContext . put ( "action" , encodedEndpointURL ) ; velocityContext . put ( "binding" , getBindingURI ( ) ) ; SAMLObject outboundMessage = messageContext . getMessage ( ) ; log . debug ( "Marshalling and Base64 encoding SAML message" ) ; Element domMessage = marshallMessage ( outboundMessage ) ; String messageXML = SerializeSupport . nodeToString ( domMessage ) ; log . trace ( "Output XML message: {}" , messageXML ) ; String encodedMessage = Base64Support . encode ( messageXML . getBytes ( StandardCharsets . UTF_8 ) , Base64Support . UNCHUNKED ) ; if ( outboundMessage instanceof RequestAbstractType ) { velocityContext . put ( "SAMLRequest" , encodedMessage ) ; } else if ( outboundMessage instanceof StatusResponseType ) { velocityContext . put ( "SAMLResponse" , encodedMessage ) ; } else { throw new MessageEncodingException ( "SAML message is neither a SAML RequestAbstractType or StatusResponseType" ) ; } String relayState = SAMLBindingSupport . getRelayState ( messageContext ) ; if ( SAMLBindingSupport . checkRelayState ( relayState ) ) { String encodedRelayState = HTMLEncoder . encodeForHTMLAttribute ( relayState ) ; log . debug ( "Setting RelayState parameter to: '{}', encoded as '{}'" , relayState , encodedRelayState ) ; velocityContext . put ( "RelayState" , encodedRelayState ) ; } }
Populate the Velocity context instance which will be used to render the POST body .
25,225
protected Element marshallMessage ( XMLObject message ) throws MessageEncodingException { log . debug ( "Marshalling message" ) ; try { return XMLObjectSupport . marshall ( message ) ; } catch ( MarshallingException e ) { throw new MessageEncodingException ( "Error marshalling message" , e ) ; } }
Helper method that marshalls the given message .
25,226
public List < U > getAll ( final boolean readFromSession ) { final LinkedHashMap < String , U > profiles = retrieveAll ( readFromSession ) ; return ProfileHelper . flatIntoAProfileList ( profiles ) ; }
Retrieve all user profiles .
25,227
protected LinkedHashMap < String , U > retrieveAll ( final boolean readFromSession ) { final LinkedHashMap < String , U > profiles = new LinkedHashMap < > ( ) ; this . context . getRequestAttribute ( Pac4jConstants . USER_PROFILES ) . ifPresent ( request -> { if ( request instanceof LinkedHashMap ) { profiles . putAll ( ( LinkedHashMap < String , U > ) request ) ; } if ( request instanceof CommonProfile ) { profiles . put ( retrieveClientName ( ( U ) request ) , ( U ) request ) ; } } ) ; if ( readFromSession ) { this . sessionStore . get ( this . context , Pac4jConstants . USER_PROFILES ) . ifPresent ( sessionAttribute -> { if ( sessionAttribute instanceof LinkedHashMap ) { profiles . putAll ( ( LinkedHashMap < String , U > ) sessionAttribute ) ; } if ( sessionAttribute instanceof CommonProfile ) { profiles . put ( retrieveClientName ( ( U ) sessionAttribute ) , ( U ) sessionAttribute ) ; } } ) ; } removeExpiredProfiles ( profiles ) ; return profiles ; }
Retrieve the map of profiles from the session or the request .
25,228
public Object prepare ( final Object value ) { if ( value == null || value instanceof String || ! stringify ) { return value ; } else { if ( value instanceof Boolean ) { return PREFIX_BOOLEAN . concat ( value . toString ( ) ) ; } else if ( value instanceof Integer ) { return PREFIX_INT . concat ( value . toString ( ) ) ; } else if ( value instanceof Long ) { return PREFIX_LONG . concat ( value . toString ( ) ) ; } else if ( value instanceof Date ) { return PREFIX_DATE . concat ( newSdf ( ) . format ( ( Date ) value ) ) ; } else if ( value instanceof URI ) { return PREFIX_URI . concat ( value . toString ( ) ) ; } else { return PREFIX_SB64 . concat ( serializationHelper . serializeToBase64 ( ( Serializable ) value ) ) ; } } }
Before saving the attribute into the attributes map .
25,229
public Object restore ( final Object value ) { if ( value != null && value instanceof String ) { final String sValue = ( String ) value ; if ( sValue . startsWith ( PREFIX ) ) { if ( sValue . startsWith ( PREFIX_BOOLEAN ) ) { return Boolean . parseBoolean ( sValue . substring ( PREFIX_BOOLEAN . length ( ) ) ) ; } else if ( sValue . startsWith ( PREFIX_INT ) ) { return Integer . parseInt ( sValue . substring ( PREFIX_INT . length ( ) ) ) ; } else if ( sValue . startsWith ( PREFIX_LONG ) ) { return Long . parseLong ( sValue . substring ( PREFIX_LONG . length ( ) ) ) ; } else if ( sValue . startsWith ( PREFIX_DATE ) ) { final String d = sValue . substring ( PREFIX_DATE . length ( ) ) ; try { return newSdf ( ) . parse ( d ) ; } catch ( final ParseException e ) { logger . warn ( "Unable to parse stringified date: {}" , d , e ) ; } } else if ( sValue . startsWith ( PREFIX_URI ) ) { final String uri = sValue . substring ( PREFIX_URI . length ( ) ) ; try { return new URI ( uri ) ; } catch ( final URISyntaxException e ) { logger . warn ( "Unable to parse stringified URI: {}" , uri , e ) ; } } else if ( sValue . startsWith ( PREFIX_SB64 ) ) { return serializationHelper . deserializeFromBase64 ( sValue . substring ( PREFIX_SB64 . length ( ) ) ) ; } } } return value ; }
After retrieving the attribute from the attributes map .
25,230
public static EntryResolver newSearchEntryResolver ( final LdapAuthenticationProperties l ) { final PooledSearchEntryResolver entryResolver = new PooledSearchEntryResolver ( ) ; entryResolver . setBaseDn ( l . getBaseDn ( ) ) ; entryResolver . setUserFilter ( l . getUserFilter ( ) ) ; entryResolver . setSubtreeSearch ( l . isSubtreeSearch ( ) ) ; entryResolver . setConnectionFactory ( LdaptiveAuthenticatorBuilder . newPooledConnectionFactory ( l ) ) ; return entryResolver ; }
New dn resolver entry resolver .
25,231
public S buildService ( final WebContext context , final IndirectClient client , final String state ) { init ( ) ; final String finalCallbackUrl = client . computeFinalCallbackUrl ( context ) ; return getApi ( ) . createService ( this . key , this . secret , finalCallbackUrl , this . scope , null , state , this . responseType , null , this . httpClientConfig , null ) ; }
Build an OAuth service from the web context and with a state .
25,232
public boolean isAllAuthorized ( final WebContext context , final List < U > profiles ) { for ( final U profile : profiles ) { if ( ! isProfileAuthorized ( context , profile ) ) { return handleError ( context ) ; } } return true ; }
If all profiles are authorized .
25,233
protected void populateBindingContext ( final SAML2MessageContext messageContext ) { SAMLBindingContext bindingContext = messageContext . getSubcontext ( SAMLBindingContext . class , true ) ; bindingContext . setBindingUri ( getBindingURI ( messageContext ) ) ; bindingContext . setHasBindingSignature ( false ) ; bindingContext . setIntendedDestinationEndpointURIRequired ( SAMLBindingSupport . isMessageSigned ( messageContext ) ) ; }
Populate the context which carries information specific to this binding .
25,234
protected XMLObject unmarshallMessage ( InputStream messageStream ) throws MessageDecodingException { try { XMLObject message = XMLObjectSupport . unmarshallFromInputStream ( getParserPool ( ) , messageStream ) ; return message ; } catch ( XMLParserException e ) { throw new MessageDecodingException ( "Error unmarshalling message from input stream" , e ) ; } catch ( UnmarshallingException e ) { throw new MessageDecodingException ( "Error unmarshalling message from input stream" , e ) ; } }
Helper method that deserializes and unmarshalls the message from the given stream .
25,235
protected Map < String , Object > convertProfileAndPasswordToAttributes ( final U profile , final String password ) { final Map < String , Object > storageAttributes = new HashMap < > ( ) ; storageAttributes . put ( getIdAttribute ( ) , profile . getId ( ) ) ; storageAttributes . put ( LINKEDID , profile . getLinkedId ( ) ) ; storageAttributes . put ( getUsernameAttribute ( ) , profile . getUsername ( ) ) ; if ( isNotBlank ( password ) ) { final String encodedPassword ; if ( passwordEncoder != null ) { encodedPassword = passwordEncoder . encode ( password ) ; } else { encodedPassword = password ; } storageAttributes . put ( getPasswordAttribute ( ) , encodedPassword ) ; } if ( isLegacyMode ( ) ) { for ( final String attributeName : attributeNames ) { storageAttributes . put ( attributeName , profile . getAttribute ( attributeName ) ) ; } } else { storageAttributes . put ( SERIALIZED_PROFILE , javaSerializationHelper . serializeToBase64 ( profile ) ) ; } return storageAttributes ; }
Convert a profile and a password into a map of attributes for the storage .
25,236
protected List < String > defineAttributesToRead ( ) { final List < String > names = new ArrayList < > ( ) ; names . add ( getIdAttribute ( ) ) ; names . add ( LINKEDID ) ; if ( isLegacyMode ( ) ) { names . add ( getUsernameAttribute ( ) ) ; names . addAll ( Arrays . asList ( attributeNames ) ) ; } else { names . add ( SERIALIZED_PROFILE ) ; } return names ; }
Define the attributes to read in the storage .
25,237
protected U convertAttributesToProfile ( final List < Map < String , Object > > listStorageAttributes , final String username ) { if ( listStorageAttributes == null || listStorageAttributes . size ( ) == 0 ) { return null ; } final Map < String , Object > storageAttributes = listStorageAttributes . get ( 0 ) ; final String linkedId = ( String ) storageAttributes . get ( LINKEDID ) ; if ( isLegacyMode ( ) ) { final U profile = getProfileDefinition ( ) . newProfile ( ) ; for ( final String attributeName : attributeNames ) { getProfileDefinition ( ) . convertAndAdd ( profile , PROFILE_ATTRIBUTE , attributeName , storageAttributes . get ( attributeName ) ) ; } final Object retrievedUsername = storageAttributes . get ( getUsernameAttribute ( ) ) ; if ( retrievedUsername != null ) { profile . setId ( ProfileHelper . sanitizeIdentifier ( profile , retrievedUsername ) ) ; } else { profile . setId ( username ) ; } if ( isNotBlank ( linkedId ) ) { profile . setLinkedId ( linkedId ) ; } return profile ; } else { final String serializedProfile = ( String ) storageAttributes . get ( SERIALIZED_PROFILE ) ; if ( serializedProfile == null ) { throw new TechnicalException ( "No serialized profile found. You should certainly define the explicit attribute names you " + "want to retrieve" ) ; } final U profile = ( U ) javaSerializationHelper . deserializeFromBase64 ( serializedProfile ) ; if ( profile == null ) { throw new TechnicalException ( "No deserialized profile available. You should certainly define the explicit attribute " + "names you want to retrieve" ) ; } final Object id = storageAttributes . get ( getIdAttribute ( ) ) ; if ( isBlank ( profile . getId ( ) ) && id != null ) { profile . setId ( ProfileHelper . sanitizeIdentifier ( profile , id ) ) ; } if ( isBlank ( profile . getLinkedId ( ) ) && isNotBlank ( linkedId ) ) { profile . setLinkedId ( linkedId ) ; } return profile ; } }
Convert the list of map of attributes from the storage into a profile .
25,238
public static RedirectionAction buildRedirectUrlAction ( final WebContext context , final String location ) { if ( ContextHelper . isPost ( context ) && useModernHttpCodes ) { return new SeeOtherAction ( location ) ; } else { return new FoundAction ( location ) ; } }
Build the appropriate redirection action for a location .
25,239
public static RedirectionAction buildFormPostContentAction ( final WebContext context , final String content ) { if ( ContextHelper . isPost ( context ) && useModernHttpCodes ) { return new TemporaryRedirectAction ( content ) ; } else { return new OkAction ( content ) ; } }
Build the appropriate redirection action for a content which is a form post .
25,240
public static String buildFormPostContent ( final WebContext context ) { final String requestedUrl = context . getFullRequestURL ( ) ; final Map < String , String [ ] > parameters = context . getRequestParameters ( ) ; final StringBuilder buffer = new StringBuilder ( ) ; buffer . append ( "<html>\n" ) ; buffer . append ( "<body>\n" ) ; buffer . append ( "<form action=\"" + escapeHtml ( requestedUrl ) + "\" name=\"f\" method=\"post\">\n" ) ; if ( parameters != null ) { for ( final Map . Entry < String , String [ ] > entry : parameters . entrySet ( ) ) { final String [ ] values = entry . getValue ( ) ; if ( values != null && values . length > 0 ) { buffer . append ( "<input type='hidden' name=\"" + escapeHtml ( entry . getKey ( ) ) + "\" value=\"" + values [ 0 ] + "\" />\n" ) ; } } } buffer . append ( "<input value='POST' type='submit' />\n" ) ; buffer . append ( "</form>\n" ) ; buffer . append ( "<script type='text/javascript'>document.forms['f'].submit();</script>\n" ) ; buffer . append ( "</body>\n" ) ; buffer . append ( "</html>\n" ) ; return buffer . toString ( ) ; }
Build a form POST content from the web context .
25,241
public void convertAndAdd ( final CommonProfile profile , final AttributeLocation attributeLocation , final String name , final Object value ) { if ( value != null ) { final Object convertedValue ; final AttributeConverter < ? extends Object > converter = this . converters . get ( name ) ; if ( converter != null ) { convertedValue = converter . convert ( value ) ; if ( convertedValue != null ) { logger . debug ( "converted to => key: {} / value: {} / {}" , name , convertedValue , convertedValue . getClass ( ) ) ; } } else { convertedValue = value ; logger . debug ( "no conversion => key: {} / value: {} / {}" , name , convertedValue , convertedValue . getClass ( ) ) ; } if ( attributeLocation . equals ( AUTHENTICATION_ATTRIBUTE ) ) { profile . addAuthenticationAttribute ( name , convertedValue ) ; } else { profile . addAttribute ( name , convertedValue ) ; } } }
Convert a profile or authentication attribute if necessary and add it to the profile .
25,242
public void convertAndAdd ( final CommonProfile profile , final Map < String , Object > profileAttributes , final Map < String , Object > authenticationAttributes ) { if ( profileAttributes != null ) { profileAttributes . entrySet ( ) . stream ( ) . forEach ( entry -> convertAndAdd ( profile , PROFILE_ATTRIBUTE , entry . getKey ( ) , entry . getValue ( ) ) ) ; } if ( authenticationAttributes != null ) { authenticationAttributes . entrySet ( ) . stream ( ) . forEach ( entry -> convertAndAdd ( profile , AUTHENTICATION_ATTRIBUTE , entry . getKey ( ) , entry . getValue ( ) ) ) ; } }
Convert the profile and authentication attributes if necessary and add them to the profile .
25,243
protected void setProfileFactory ( final Function < Object [ ] , P > profileFactory ) { CommonHelper . assertNotNull ( "profileFactory" , profileFactory ) ; this . newProfile = profileFactory ; }
Define the way to build the profile .
25,244
protected void secondary ( final String name , final AttributeConverter < ? extends Object > converter ) { secondaries . add ( name ) ; converters . put ( name , converter ) ; }
Add an attribute as a secondary one and its converter .
25,245
protected void removeSignature ( SAMLObject message ) { if ( message instanceof SignableSAMLObject ) { final SignableSAMLObject signableMessage = ( SignableSAMLObject ) message ; if ( signableMessage . isSigned ( ) ) { log . debug ( "Removing SAML protocol message signature" ) ; signableMessage . setSignature ( null ) ; } } }
Removes the signature from the protocol message .
25,246
protected String buildRedirectURL ( MessageContext < SAMLObject > messageContext , String endpoint , String message ) throws MessageEncodingException { log . debug ( "Building URL to redirect client to" ) ; URLBuilder urlBuilder ; try { urlBuilder = new URLBuilder ( endpoint ) ; } catch ( MalformedURLException e ) { throw new MessageEncodingException ( "Endpoint URL " + endpoint + " is not a valid URL" , e ) ; } List < Pair < String , String > > queryParams = urlBuilder . getQueryParams ( ) ; queryParams . clear ( ) ; SAMLObject outboundMessage = messageContext . getMessage ( ) ; if ( outboundMessage instanceof RequestAbstractType ) { queryParams . add ( new Pair < > ( "SAMLRequest" , message ) ) ; } else if ( outboundMessage instanceof StatusResponseType ) { queryParams . add ( new Pair < > ( "SAMLResponse" , message ) ) ; } else { throw new MessageEncodingException ( "SAML message is neither a SAML RequestAbstractType or StatusResponseType" ) ; } String relayState = SAMLBindingSupport . getRelayState ( messageContext ) ; if ( SAMLBindingSupport . checkRelayState ( relayState ) ) { queryParams . add ( new Pair < > ( "RelayState" , relayState ) ) ; } SignatureSigningParameters signingParameters = SAMLMessageSecuritySupport . getContextSigningParameters ( messageContext ) ; if ( signingParameters != null && signingParameters . getSigningCredential ( ) != null ) { String sigAlgURI = getSignatureAlgorithmURI ( signingParameters ) ; Pair < String , String > sigAlg = new Pair < > ( "SigAlg" , sigAlgURI ) ; queryParams . add ( sigAlg ) ; String sigMaterial = urlBuilder . buildQueryString ( ) ; queryParams . add ( new Pair < > ( "Signature" , generateSignature ( signingParameters . getSigningCredential ( ) , sigAlgURI , sigMaterial ) ) ) ; } else { log . debug ( "No signing credential was supplied, skipping HTTP-Redirect DEFLATE signing" ) ; } return urlBuilder . buildURL ( ) ; }
Builds the URL to redirect the client to .
25,247
protected String getSignatureAlgorithmURI ( SignatureSigningParameters signingParameters ) throws MessageEncodingException { if ( signingParameters . getSignatureAlgorithm ( ) != null ) { return signingParameters . getSignatureAlgorithm ( ) ; } throw new MessageEncodingException ( "The signing algorithm URI could not be determined" ) ; }
Gets the signature algorithm URI to use .
25,248
protected String generateSignature ( Credential signingCredential , String algorithmURI , String queryString ) throws MessageEncodingException { log . debug ( String . format ( "Generating signature with key type '%s', algorithm URI '%s' over query string '%s'" , CredentialSupport . extractSigningKey ( signingCredential ) . getAlgorithm ( ) , algorithmURI , queryString ) ) ; String b64Signature ; try { byte [ ] rawSignature = XMLSigningUtil . signWithURI ( signingCredential , algorithmURI , queryString . getBytes ( StandardCharsets . UTF_8 ) ) ; b64Signature = Base64Support . encode ( rawSignature , Base64Support . UNCHUNKED ) ; log . debug ( "Generated digital signature value (base64-encoded) {}" , b64Signature ) ; } catch ( final org . opensaml . security . SecurityException e ) { throw new MessageEncodingException ( "Unable to sign URL query string" , e ) ; } return b64Signature ; }
Generates the signature over the query string .
25,249
public static JsonNode getFirstNode ( final String text , final String path ) { try { JsonNode node = mapper . readValue ( text , JsonNode . class ) ; if ( path != null ) { node = ( JsonNode ) getElement ( node , path ) ; } return node ; } catch ( final IOException e ) { logger . error ( "Cannot get first node" , e ) ; } return null ; }
Return the first node of a JSON response .
25,250
public static Object getElement ( final JsonNode json , final String name ) { if ( json != null && name != null ) { JsonNode node = json ; for ( String nodeName : name . split ( "\\." ) ) { if ( node != null ) { if ( nodeName . matches ( "\\d+" ) ) { node = node . get ( Integer . parseInt ( nodeName ) ) ; } else { node = node . get ( nodeName ) ; } } } if ( node != null ) { if ( node . isNumber ( ) ) { return node . numberValue ( ) ; } else if ( node . isBoolean ( ) ) { return node . booleanValue ( ) ; } else if ( node . isTextual ( ) ) { return node . textValue ( ) ; } else if ( node . isNull ( ) ) { return null ; } else { return node ; } } } return null ; }
Return the field with name in JSON as a string a boolean a number or a node .
25,251
public static String toJSONString ( final Object obj ) { try { return mapper . writeValueAsString ( obj ) ; } catch ( final JsonProcessingException e ) { logger . error ( "Cannot to JSON string" , e ) ; } return null ; }
Returns the JSON string for the object .
25,252
private X509Certificate createSelfSignedCert ( X500Name dn , String sigName , AlgorithmIdentifier sigAlgID , KeyPair keyPair ) throws Exception { final V3TBSCertificateGenerator certGen = new V3TBSCertificateGenerator ( ) ; certGen . setSerialNumber ( new ASN1Integer ( BigInteger . valueOf ( 1 ) ) ) ; certGen . setIssuer ( dn ) ; certGen . setSubject ( dn ) ; certGen . setStartDate ( new Time ( new Date ( System . currentTimeMillis ( ) - 1000L ) ) ) ; final Calendar c = Calendar . getInstance ( ) ; c . setTime ( new Date ( ) ) ; c . add ( Calendar . YEAR , 1 ) ; certGen . setEndDate ( new Time ( c . getTime ( ) ) ) ; certGen . setSignature ( sigAlgID ) ; certGen . setSubjectPublicKeyInfo ( SubjectPublicKeyInfo . getInstance ( keyPair . getPublic ( ) . getEncoded ( ) ) ) ; Signature sig = Signature . getInstance ( sigName ) ; sig . initSign ( keyPair . getPrivate ( ) ) ; sig . update ( certGen . generateTBSCertificate ( ) . getEncoded ( ASN1Encoding . DER ) ) ; TBSCertificate tbsCert = certGen . generateTBSCertificate ( ) ; ASN1EncodableVector v = new ASN1EncodableVector ( ) ; v . add ( tbsCert ) ; v . add ( sigAlgID ) ; v . add ( new DERBitString ( sig . sign ( ) ) ) ; final X509Certificate cert = ( X509Certificate ) CertificateFactory . getInstance ( "X.509" ) . generateCertificate ( new ByteArrayInputStream ( new DERSequence ( v ) . getEncoded ( ASN1Encoding . DER ) ) ) ; cert . verify ( keyPair . getPublic ( ) ) ; return cert ; }
Generate a self - signed certificate for dn using the provided signature algorithm and key pair .
25,253
public byte [ ] serializeToBytes ( final Serializable o ) { byte [ ] bytes = null ; try ( final ByteArrayOutputStream baos = new ByteArrayOutputStream ( ) ; final ObjectOutputStream oos = new ObjectOutputStream ( baos ) ) { oos . writeObject ( o ) ; oos . flush ( ) ; bytes = baos . toByteArray ( ) ; } catch ( final IOException e ) { logger . warn ( "cannot Java serialize object" , e ) ; } return bytes ; }
Serialize a Java object into a bytes array .
25,254
public Serializable deserializeFromBytes ( final byte [ ] bytes ) { Serializable o = null ; try ( final ByteArrayInputStream bais = new ByteArrayInputStream ( bytes ) ; final ObjectInputStream ois = new RestrictedObjectInputStream ( bais , this . trustedPackages , this . trustedClasses ) ) { o = ( Serializable ) ois . readObject ( ) ; } catch ( final IOException | ClassNotFoundException e ) { logger . warn ( "cannot Java deserialize object" , e ) ; } return o ; }
Deserialize a bytes array into a Java object .
25,255
public static String addParameter ( final String url , final String name , final String value ) { if ( url != null ) { final StringBuilder sb = new StringBuilder ( ) ; sb . append ( url ) ; if ( name != null ) { if ( url . indexOf ( "?" ) >= 0 ) { sb . append ( "&" ) ; } else { sb . append ( "?" ) ; } sb . append ( name ) ; sb . append ( "=" ) ; if ( value != null ) { sb . append ( urlEncode ( value ) ) ; } } return sb . toString ( ) ; } return null ; }
Add a new parameter to an url .
25,256
public static String urlEncode ( final String text ) { try { return URLEncoder . encode ( text , StandardCharsets . UTF_8 . name ( ) ) ; } catch ( final UnsupportedEncodingException e ) { final String message = "Unable to encode text : " + text ; throw new TechnicalException ( message , e ) ; } }
URL encode a text using UTF - 8 .
25,257
public static String toNiceString ( final Class < ? > clazz , final Object ... args ) { final StringBuilder sb = new StringBuilder ( ) ; sb . append ( "#" ) ; sb . append ( clazz . getSimpleName ( ) ) ; sb . append ( "# |" ) ; boolean b = true ; for ( final Object arg : args ) { if ( b ) { sb . append ( " " ) ; sb . append ( arg ) ; sb . append ( ":" ) ; } else { sb . append ( " " ) ; sb . append ( arg ) ; sb . append ( " |" ) ; } b = ! b ; } return sb . toString ( ) ; }
Build a nice toString for an object .
25,258
public static String randomString ( final int size ) { final StringBuilder builder = new StringBuilder ( ) ; while ( builder . length ( ) < size ) { final String suffix = java . util . UUID . randomUUID ( ) . toString ( ) . replace ( "-" , "" ) ; builder . append ( suffix ) ; } return builder . substring ( 0 , size ) ; }
Return a random string of a certain size .
25,259
public static Date newDate ( final Date original ) { return original != null ? new Date ( original . getTime ( ) ) : null ; }
Copy a date .
25,260
public static URI asURI ( final String s ) { try { return new URI ( s ) ; } catch ( final URISyntaxException e ) { throw new TechnicalException ( "Cannot make an URI from: " + s , e ) ; } }
Convert a string into an URI .
25,261
public static Constructor getConstructor ( final String name ) throws ClassNotFoundException , NoSuchMethodException { Constructor constructor = constructorsCache . get ( name ) ; if ( constructor == null ) { synchronized ( constructorsCache ) { constructor = constructorsCache . get ( name ) ; if ( constructor == null ) { ClassLoader tccl = Thread . currentThread ( ) . getContextClassLoader ( ) ; if ( tccl == null ) { constructor = Class . forName ( name ) . getDeclaredConstructor ( ) ; } else { constructor = Class . forName ( name , true , tccl ) . getDeclaredConstructor ( ) ; } constructorsCache . put ( name , constructor ) ; } } } return constructor ; }
Get the constructor of the class .
25,262
public void build ( final Object id , final Map < String , Object > attributes ) { setId ( ProfileHelper . sanitizeIdentifier ( this , id ) ) ; addAttributes ( attributes ) ; }
Build a profile from user identifier and attributes .
25,263
public void build ( final Object id , final Map < String , Object > attributes , final Map < String , Object > authenticationAttributes ) { build ( id , attributes ) ; addAuthenticationAttributes ( authenticationAttributes ) ; }
Build a profile from user identifier attributes and authentication attributes .
25,264
public void addAuthenticationAttributes ( Map < String , Object > attributeMap ) { if ( attributeMap != null ) { for ( final Map . Entry < String , Object > entry : attributeMap . entrySet ( ) ) { addAuthenticationAttribute ( entry . getKey ( ) , entry . getValue ( ) ) ; } } }
Add authentication attributes .
25,265
public Object getAttribute ( final String name ) { return ProfileHelper . getInternalAttributeHandler ( ) . restore ( this . attributes . get ( name ) ) ; }
Return the attribute with name .
25,266
public Object getAuthenticationAttribute ( final String name ) { return ProfileHelper . getInternalAttributeHandler ( ) . restore ( this . authenticationAttributes . get ( name ) ) ; }
Return the authentication attribute with name .
25,267
public boolean containsAttribute ( final String name ) { CommonHelper . assertNotNull ( "name" , name ) ; return this . attributes . containsKey ( name ) ; }
Check to see if profile contains attribute name .
25,268
public < T > T getAuthenticationAttribute ( final String name , final Class < T > clazz ) { final Object attribute = getAuthenticationAttribute ( name ) ; return getAttributeByType ( name , clazz , attribute ) ; }
Return authentication attribute with name
25,269
public void addRole ( final String role ) { CommonHelper . assertNotBlank ( "role" , role ) ; this . roles . add ( role ) ; }
Add a role .
25,270
public void addRoles ( final Collection < String > roles ) { CommonHelper . assertNotNull ( "roles" , roles ) ; this . roles . addAll ( roles ) ; }
Add roles .
25,271
public void addPermission ( final String permission ) { CommonHelper . assertNotBlank ( "permission" , permission ) ; this . permissions . add ( permission ) ; }
Add a permission .
25,272
public void addPermissions ( final Collection < String > permissions ) { CommonHelper . assertNotNull ( "permissions" , permissions ) ; this . permissions . addAll ( permissions ) ; }
Add permissions .
25,273
public boolean mustLoadProfilesFromSession ( final C context , final List < Client > currentClients ) { return isEmpty ( currentClients ) || currentClients . get ( 0 ) instanceof IndirectClient || currentClients . get ( 0 ) instanceof AnonymousClient ; }
Load the profiles from the web session if no clients are defined or if the first client is an indirect one or if the first client is the anonymous one .
25,274
public boolean mustSaveProfileInSession ( final C context , final List < Client > currentClients , final DirectClient directClient , final UserProfile profile ) { return false ; }
Never save the profile in session after a direct client authentication .
25,275
protected void updateIndirectClient ( final IndirectClient client ) { if ( this . callbackUrl != null && client . getCallbackUrl ( ) == null ) { client . setCallbackUrl ( this . callbackUrl ) ; } if ( this . urlResolver != null && client . getUrlResolver ( ) == null ) { client . setUrlResolver ( this . urlResolver ) ; } if ( this . callbackUrlResolver != null && client . getCallbackUrlResolver ( ) == null ) { client . setCallbackUrlResolver ( this . callbackUrlResolver ) ; } if ( this . ajaxRequestResolver != null && client . getAjaxRequestResolver ( ) == null ) { client . setAjaxRequestResolver ( this . ajaxRequestResolver ) ; } }
Setup the indirect client .
25,276
public Optional < Client > findClient ( final String name ) { CommonHelper . assertNotBlank ( "name" , name ) ; init ( ) ; final String lowerTrimmedName = name . toLowerCase ( ) . trim ( ) ; final Client client = _clients . get ( lowerTrimmedName ) ; if ( client != null ) { return Optional . of ( client ) ; } LOGGER . debug ( "No client found for name: {}" , name ) ; return Optional . empty ( ) ; }
Return the right client according to the specific name .
25,277
@ SuppressWarnings ( "unchecked" ) public < C extends Client > Optional < C > findClient ( final Class < C > clazz ) { CommonHelper . assertNotNull ( "clazz" , clazz ) ; init ( ) ; if ( clazz != null ) { for ( final Client client : getClients ( ) ) { if ( clazz . isAssignableFrom ( client . getClass ( ) ) ) { return Optional . of ( ( C ) client ) ; } } } LOGGER . debug ( "No client found for class: {}" , clazz ) ; return Optional . empty ( ) ; }
Return the right client according to the specific class .
25,278
protected String getSessionIndex ( final Assertion subjectAssertion ) { List < AuthnStatement > authnStatements = subjectAssertion . getAuthnStatements ( ) ; if ( authnStatements != null && authnStatements . size ( ) > 0 ) { AuthnStatement statement = authnStatements . get ( 0 ) ; if ( statement != null ) { return statement . getSessionIndex ( ) ; } } return null ; }
Searches the sessionIndex in the assertion
25,279
protected final void decryptEncryptedAssertions ( final Response response , final Decrypter decrypter ) { for ( final EncryptedAssertion encryptedAssertion : response . getEncryptedAssertions ( ) ) { try { final Assertion decryptedAssertion = decrypter . decrypt ( encryptedAssertion ) ; response . getAssertions ( ) . add ( decryptedAssertion ) ; } catch ( final DecryptionException e ) { logger . error ( "Decryption of assertion failed, continue with the next one" , e ) ; } } }
Decrypt encrypted assertions and add them to the assertions list of the response .
25,280
protected final boolean isValidBearerSubjectConfirmationData ( final SubjectConfirmationData data , final SAML2MessageContext context ) { if ( data == null ) { logger . debug ( "SubjectConfirmationData cannot be null for Bearer confirmation" ) ; return false ; } if ( data . getNotBefore ( ) != null ) { logger . debug ( "SubjectConfirmationData notBefore must be null for Bearer confirmation" ) ; return false ; } if ( data . getNotOnOrAfter ( ) == null ) { logger . debug ( "SubjectConfirmationData notOnOrAfter cannot be null for Bearer confirmation" ) ; return false ; } if ( data . getNotOnOrAfter ( ) . plusSeconds ( acceptedSkew ) . isBeforeNow ( ) ) { logger . debug ( "SubjectConfirmationData notOnOrAfter is too old" ) ; return false ; } try { if ( data . getRecipient ( ) == null ) { logger . debug ( "SubjectConfirmationData recipient cannot be null for Bearer confirmation" ) ; return false ; } else { final Endpoint endpoint = context . getSAMLEndpointContext ( ) . getEndpoint ( ) ; if ( endpoint == null ) { logger . warn ( "No endpoint was found in the SAML endpoint context" ) ; return false ; } final URI recipientUri = new URI ( data . getRecipient ( ) ) ; final URI appEndpointUri = new URI ( endpoint . getLocation ( ) ) ; if ( ! SAML2Utils . urisEqualAfterPortNormalization ( recipientUri , appEndpointUri ) ) { logger . debug ( "SubjectConfirmationData recipient {} does not match SP assertion consumer URL, found. " + "SP ACS URL from context: {}" , recipientUri , appEndpointUri ) ; return false ; } } } catch ( URISyntaxException use ) { logger . error ( "Unable to check SubjectConfirmationData recipient, a URI has invalid syntax." , use ) ; return false ; } return true ; }
Validate Bearer subject confirmation data - notBefore - NotOnOrAfter - recipient
25,281
protected final void validateAssertionConditions ( final Conditions conditions , final SAML2MessageContext context ) { if ( conditions == null ) { return ; } if ( conditions . getNotBefore ( ) != null && conditions . getNotBefore ( ) . minusSeconds ( acceptedSkew ) . isAfterNow ( ) ) { throw new SAMLAssertionConditionException ( "Assertion condition notBefore is not valid" ) ; } if ( conditions . getNotOnOrAfter ( ) != null && conditions . getNotOnOrAfter ( ) . plusSeconds ( acceptedSkew ) . isBeforeNow ( ) ) { throw new SAMLAssertionConditionException ( "Assertion condition notOnOrAfter is not valid" ) ; } final String entityId = context . getSAMLSelfEntityContext ( ) . getEntityId ( ) ; validateAudienceRestrictions ( conditions . getAudienceRestrictions ( ) , entityId ) ; }
Validate assertionConditions - notBefore - notOnOrAfter
25,282
protected final void validateAudienceRestrictions ( final List < AudienceRestriction > audienceRestrictions , final String spEntityId ) { if ( audienceRestrictions == null || audienceRestrictions . isEmpty ( ) ) { throw new SAMLAssertionAudienceException ( "Audience restrictions cannot be null or empty" ) ; } final Set < String > audienceUris = new HashSet < > ( ) ; for ( final AudienceRestriction audienceRestriction : audienceRestrictions ) { if ( audienceRestriction . getAudiences ( ) != null ) { for ( final Audience audience : audienceRestriction . getAudiences ( ) ) { audienceUris . add ( audience . getAudienceURI ( ) ) ; } } } if ( ! audienceUris . contains ( spEntityId ) ) { throw new SAMLAssertionAudienceException ( "Assertion audience " + audienceUris + " does not match SP configuration " + spEntityId ) ; } }
Validate audience by matching the SP entityId .
25,283
protected final void validateAssertionSignature ( final Signature signature , final SAML2MessageContext context , final SignatureTrustEngine engine ) { final SAMLPeerEntityContext peerContext = context . getSAMLPeerEntityContext ( ) ; if ( signature != null ) { final String entityId = peerContext . getEntityId ( ) ; validateSignature ( signature , entityId , engine ) ; } else { if ( wantsAssertionsSigned ( context ) && ! peerContext . isAuthenticated ( ) ) { throw new SAMLSignatureRequiredException ( "Assertion or response must be signed" ) ; } } }
Validate assertion signature . If none is found and the SAML response did not have one and the SP requires the assertions to be signed the validation fails .
25,284
public void set ( final String messageID , final XMLObject message ) { log . debug ( "Storing message {} to session {}" , messageID , context . getSessionStore ( ) . getOrCreateSessionId ( context ) ) ; final LinkedHashMap < String , XMLObject > messages = getMessages ( ) ; messages . put ( messageID , message ) ; updateSession ( messages ) ; }
Stores a request message into the repository . RequestAbstractType must have an ID set . Any previous message with the same ID will be overwritten .
25,285
private void updateSession ( final LinkedHashMap < String , XMLObject > messages ) { context . getSessionStore ( ) . set ( context , SAML_STORAGE_KEY , messages ) ; }
Updates session with the internalMessages key . Some application servers require session value to be updated in order to replicate the session across nodes or persist it correctly .
25,286
public String getProxyTicketFor ( final String service ) { if ( this . attributePrincipal != null ) { logger . debug ( "Requesting PT from principal: {} and for service: {}" , attributePrincipal , service ) ; final String pt = this . attributePrincipal . getProxyTicketFor ( service ) ; logger . debug ( "Get PT: {}" , pt ) ; return pt ; } return null ; }
Get a proxy ticket for a given service .
25,287
protected Optional < C > retrieveCredentials ( final WebContext context ) { try { final Optional < C > optCredentials = this . credentialsExtractor . extract ( context ) ; optCredentials . ifPresent ( credentials -> { final long t0 = System . currentTimeMillis ( ) ; try { this . authenticator . validate ( credentials , context ) ; } finally { final long t1 = System . currentTimeMillis ( ) ; logger . debug ( "Credentials validation took: {} ms" , t1 - t0 ) ; } } ) ; return optCredentials ; } catch ( CredentialsException e ) { logger . info ( "Failed to retrieve or validate credentials: {}" , e . getMessage ( ) ) ; logger . debug ( "Failed to retrieve or validate credentials" , e ) ; return Optional . empty ( ) ; } }
Retrieve the credentials .
25,288
protected final Optional < UserProfile > retrieveUserProfile ( final C credentials , final WebContext context ) { final Optional < UserProfile > profile = this . profileCreator . create ( credentials , context ) ; logger . debug ( "profile: {}" , profile ) ; return profile ; }
Retrieve a user profile .
25,289
protected HttpAction forbidden ( final C context , final List < Client > currentClients , final List < UserProfile > profiles , final String authorizers ) { return ForbiddenAction . INSTANCE ; }
Return a forbidden error .
25,290
protected boolean startAuthentication ( final C context , final List < Client > currentClients ) { return isNotEmpty ( currentClients ) && currentClients . get ( 0 ) instanceof IndirectClient ; }
Return whether we must start a login process if the first client is an indirect one .
25,291
protected void saveRequestedUrl ( final C context , final List < Client > currentClients , AjaxRequestResolver ajaxRequestResolver ) { if ( ajaxRequestResolver == null || ! ajaxRequestResolver . isAjax ( context ) ) { savedRequestHandler . save ( context ) ; } }
Save the requested url .
25,292
protected HttpAction redirectToIdentityProvider ( final C context , final List < Client > currentClients ) { final IndirectClient currentClient = ( IndirectClient ) currentClients . get ( 0 ) ; return ( HttpAction ) currentClient . redirect ( context ) . get ( ) ; }
Perform a redirection to start the login process of the first indirect client .
25,293
public Gender getGender ( ) { final Gender gender = ( Gender ) getAttribute ( CommonProfileDefinition . GENDER ) ; if ( gender == null ) { return Gender . UNSPECIFIED ; } else { return gender ; } }
Return the gender of the user .
25,294
protected Optional < DigestCredentials > retrieveCredentials ( final WebContext context ) { final String nonce = calculateNonce ( ) ; context . setResponseHeader ( HttpConstants . AUTHENTICATE_HEADER , "Digest realm=\"" + realm + "\", qop=\"auth\", nonce=\"" + nonce + "\"" ) ; return super . retrieveCredentials ( context ) ; }
Per RFC 2617 If a server receives a request for an access - protected object and an acceptable Authorization header is not sent the server responds with a 401 Unauthorized status code and a WWW - Authenticate header
25,295
public String calculateServerDigest ( boolean passwordAlreadyEncoded , String password ) { return generateDigest ( passwordAlreadyEncoded , username , realm , password , httpMethod , uri , qop , nonce , nc , cnonce ) ; }
This calculates the server digest value based on user stored password . If the server stores password in clear format then passwordAlreadyEncoded should be false . If the server stores the password in ha1 digest then the passwordAlreadyEncoded should be true .
25,296
private String generateDigest ( boolean passwordAlreadyEncoded , String username , String realm , String password , String httpMethod , String uri , String qop , String nonce , String nc , String cnonce ) { String ha1 ; String a2 = httpMethod + ":" + uri ; String ha2 = CredentialUtil . encryptMD5 ( a2 ) ; if ( passwordAlreadyEncoded ) { ha1 = password ; } else { ha1 = CredentialUtil . encryptMD5 ( username + ":" + realm + ":" + password ) ; } String digest ; if ( qop == null ) { digest = CredentialUtil . encryptMD5 ( ha1 , nonce + ":" + ha2 ) ; } else if ( "auth" . equals ( qop ) ) { digest = CredentialUtil . encryptMD5 ( ha1 , nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + ha2 ) ; } else { throw new TechnicalException ( "Invalid qop: '" + qop + "'" ) ; } return digest ; }
generate digest token based on RFC 2069 and RFC 2617 guidelines
25,297
protected Optional < UserProfile > retrieveUserProfileFromToken ( final WebContext context , final T accessToken ) { final OAuthProfileDefinition < U , T , O > profileDefinition = configuration . getProfileDefinition ( ) ; final String profileUrl = profileDefinition . getProfileUrl ( accessToken , configuration ) ; final S service = this . configuration . buildService ( context , client , null ) ; final String body = sendRequestForData ( service , accessToken , profileUrl , profileDefinition . getProfileVerb ( ) ) ; logger . info ( "UserProfile: " + body ) ; if ( body == null ) { throw new HttpCommunicationException ( "No data found for accessToken: " + accessToken ) ; } final U profile = ( U ) configuration . getProfileDefinition ( ) . extractUserProfile ( body ) ; addAccessTokenToProfile ( profile , accessToken ) ; return Optional . of ( profile ) ; }
Retrieve the user profile from the access token .
25,298
protected String sendRequestForData ( final S service , final T accessToken , final String dataUrl , Verb verb ) { logger . debug ( "accessToken: {} / dataUrl: {}" , accessToken , dataUrl ) ; final long t0 = System . currentTimeMillis ( ) ; final OAuthRequest request = createOAuthRequest ( dataUrl , verb ) ; signRequest ( service , accessToken , request ) ; final String body ; final int code ; try { Response response = service . execute ( request ) ; code = response . getCode ( ) ; body = response . getBody ( ) ; } catch ( final IOException | InterruptedException | ExecutionException e ) { throw new HttpCommunicationException ( "Error getting body: " + e . getMessage ( ) ) ; } final long t1 = System . currentTimeMillis ( ) ; logger . debug ( "Request took: " + ( t1 - t0 ) + " ms for: " + dataUrl ) ; logger . debug ( "response code: {} / response body: {}" , code , body ) ; if ( code != 200 ) { throw new HttpCommunicationException ( code , body ) ; } return body ; }
Make a request to get the data of the authenticated user for the provider .
25,299
protected String addExchangeToken ( final String url , final OAuth2AccessToken accessToken ) { final FacebookProfileDefinition profileDefinition = ( FacebookProfileDefinition ) configuration . getProfileDefinition ( ) ; final FacebookConfiguration facebookConfiguration = ( FacebookConfiguration ) configuration ; String computedUrl = url ; if ( facebookConfiguration . isUseAppsecretProof ( ) ) { computedUrl = profileDefinition . computeAppSecretProof ( computedUrl , accessToken , facebookConfiguration ) ; } return CommonHelper . addParameter ( computedUrl , EXCHANGE_TOKEN_PARAMETER , accessToken . getAccessToken ( ) ) ; }
Adds the token to the URL in question . If we require appsecret_proof then this method will also add the appsecret_proof parameter to the URL as Facebook expects .