signature:
public class CasAuthenticationFilter { /** * Overridden to provide proxying capabilities . */
protected boolean requiresAuthentication ( final HttpServletRequest request , final HttpServletResponse response ) { } }

implementation: final boolean serviceTicketRequest = serviceTicketRequest ( request , response ) ; final boolean result = serviceTicketRequest || proxyReceptorRequest ( request ) || ( proxyTicketRequest ( serviceTicketRequest , request ) ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "requiresAuthentication = " + result ) ; } return result ;


signature:
public class CasAuthenticationFilter { /** * Indicates if the request is elgible to process a service ticket . This method exists
 * for readability .
 * @ param request
 * @ param response
 * @ return */
private boolean serviceTicketRequest ( final HttpServletRequest request , final HttpServletResponse response ) { } }

implementation: boolean result = super . requiresAuthentication ( request , response ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "serviceTicketRequest = " + result ) ; } return result ;


signature:
public class CasAuthenticationFilter { /** * Indicates if the request is elgible to process a proxy ticket .
 * @ param request
 * @ return */
private boolean proxyTicketRequest ( final boolean serviceTicketRequest , final HttpServletRequest request ) { } }

implementation: if ( serviceTicketRequest ) { return false ; } final boolean result = authenticateAllArtifacts && obtainArtifact ( request ) != null && ! authenticated ( ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "proxyTicketRequest = " + result ) ; } return result ;


signature:
public class CasAuthenticationFilter { /** * Determines if a user is already authenticated .
 * @ return */
private boolean authenticated ( ) { } }

implementation: Authentication authentication = SecurityContextHolder . getContext ( ) . getAuthentication ( ) ; return authentication != null && authentication . isAuthenticated ( ) && ! ( authentication instanceof AnonymousAuthenticationToken ) ;


signature:
public class CasAuthenticationFilter { /** * Indicates if the request is elgible to be processed as the proxy receptor .
 * @ param request
 * @ return */
private boolean proxyReceptorRequest ( final HttpServletRequest request ) { } }

implementation: final boolean result = proxyReceptorConfigured ( ) && proxyReceptorMatcher . matches ( request ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "proxyReceptorRequest = " + result ) ; } return result ;


signature:
public class CasAuthenticationFilter { /** * Determines if the { @ link CasAuthenticationFilter } is configured to handle the proxy
 * receptor requests .
 * @ return */
private boolean proxyReceptorConfigured ( ) { } }

implementation: final boolean result = this . proxyGrantingTicketStorage != null && proxyReceptorMatcher != null ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "proxyReceptorConfigured = " + result ) ; } return result ;


signature:
public class JdbcUserDetailsManager { /** * Executes the SQL < tt > usersByUsernameQuery < / tt > and returns a list of UserDetails
 * objects . There should normally only be one matching user . */
protected List < UserDetails > loadUsersByUsername ( String username ) { } }

implementation:
return getJdbcTemplate ( ) . query ( getUsersByUsernameQuery ( ) , new String [ ] { username } , ( rs , rowNum ) -> { String userName = rs . getString ( 1 ) ; String password = rs . getString ( 2 ) ; boolean enabled = rs . getBoolean ( 3 ) ; boolean accLocked = false ; boolean accExpired = false ; boolean credsExpired = false ; if ( rs . getMetaData ( ) . getColumnCount ( ) > 3 ) { // NOTE : acc _ locked , acc _ expired and creds _ expired are also to be loaded
accLocked = rs . getBoolean ( 4 ) ; accExpired = rs . getBoolean ( 5 ) ; credsExpired = rs . getBoolean ( 6 ) ; } return new User ( userName , password , enabled , ! accExpired , ! credsExpired , ! accLocked , AuthorityUtils . NO_AUTHORITIES ) ; } ) ;


signature:
public class SecurityWebApplicationContextUtils { /** * Find a unique { @ code WebApplicationContext } for this web app : either the
 * root web app context ( preferred ) or a unique { @ code WebApplicationContext }
 * among the registered { @ code ServletContext } attributes ( typically coming
 * from a single { @ code DispatcherServlet } in the current web application ) .
 * < p > Note that { @ code DispatcherServlet } ' s exposure of its context can be
 * controlled through its { @ code publishContext } property , which is { @ code true }
 * by default but can be selectively switched to only publish a single context
 * despite multiple { @ code DispatcherServlet } registrations in the web app .
 * @ param servletContext ServletContext to find the web application context for
 * @ return the desired WebApplicationContext for this web app
 * @ see # getWebApplicationContext ( ServletContext )
 * @ see ServletContext # getAttributeNames ( )
 * @ throws IllegalStateException if no WebApplicationContext can be found */
public static WebApplicationContext findRequiredWebApplicationContext ( ServletContext servletContext ) { } }

implementation: WebApplicationContext wac = _findWebApplicationContext ( servletContext ) ; if ( wac == null ) { throw new IllegalStateException ( "No WebApplicationContext found: no ContextLoaderListener registered?" ) ; } return wac ;


signature:
public class SecurityWebApplicationContextUtils { /** * Copy of { @ link # findWebApplicationContext ( ServletContext ) } for compatibility with spring framework 4.1 . x .
 * @ see # findWebApplicationContext ( ServletContext ) */
private static WebApplicationContext _findWebApplicationContext ( ServletContext sc ) { } }

implementation: WebApplicationContext wac = getWebApplicationContext ( sc ) ; if ( wac == null ) { Enumeration < String > attrNames = sc . getAttributeNames ( ) ; while ( attrNames . hasMoreElements ( ) ) { String attrName = attrNames . nextElement ( ) ; Object attrValue = sc . getAttribute ( attrName ) ; if ( attrValue instanceof WebApplicationContext ) { if ( wac != null ) { throw new IllegalStateException ( "No unique WebApplicationContext found: more than one " + "DispatcherServlet registered with publishContext=true?" ) ; } wac = ( WebApplicationContext ) attrValue ; } } } return wac ;


signature:
public class DefaultMethodSecurityExpressionHandler { /** * Uses a { @ link MethodSecurityEvaluationContext } as the < tt > EvaluationContext < / tt >
 * implementation . */
public StandardEvaluationContext createEvaluationContextInternal ( Authentication auth , MethodInvocation mi ) { } }

implementation: return new MethodSecurityEvaluationContext ( auth , mi , getParameterNameDiscoverer ( ) ) ;


signature:
public class DefaultMethodSecurityExpressionHandler { /** * Creates the root object for expression evaluation . */
protected MethodSecurityExpressionOperations createSecurityExpressionRoot ( Authentication authentication , MethodInvocation invocation ) { } }

implementation: MethodSecurityExpressionRoot root = new MethodSecurityExpressionRoot ( authentication ) ; root . setThis ( invocation . getThis ( ) ) ; root . setPermissionEvaluator ( getPermissionEvaluator ( ) ) ; root . setTrustResolver ( getTrustResolver ( ) ) ; root . setRoleHierarchy ( getRoleHierarchy ( ) ) ; root . setDefaultRolePrefix ( getDefaultRolePrefix ( ) ) ; return root ;


signature:
public class DefaultMethodSecurityExpressionHandler { /** * Filters the { @ code filterTarget } object ( which must be either a collection , array ,
 * or stream ) , by evaluating the supplied expression .
 * If a { @ code Collection } is used , the original instance will be modified to contain
 * the elements for which the permission expression evaluates to { @ code true } . For an
 * array , a new array instance will be returned . */
@ SuppressWarnings ( "unchecked" ) public Object filter ( Object filterTarget , Expression filterExpression , EvaluationContext ctx ) { } }

implementation: MethodSecurityExpressionOperations rootObject = ( MethodSecurityExpressionOperations ) ctx . getRootObject ( ) . getValue ( ) ; final boolean debug = logger . isDebugEnabled ( ) ; List retainList ; if ( debug ) { logger . debug ( "Filtering with expression: " + filterExpression . getExpressionString ( ) ) ; } if ( filterTarget instanceof Collection ) { Collection collection = ( Collection ) filterTarget ; retainList = new ArrayList ( collection . size ( ) ) ; if ( debug ) { logger . debug ( "Filtering collection with " + collection . size ( ) + " elements" ) ; } if ( permissionCacheOptimizer != null ) { permissionCacheOptimizer . cachePermissionsFor ( rootObject . getAuthentication ( ) , collection ) ; } for ( Object filterObject : ( Collection ) filterTarget ) { rootObject . setFilterObject ( filterObject ) ; if ( ExpressionUtils . evaluateAsBoolean ( filterExpression , ctx ) ) { retainList . add ( filterObject ) ; } } if ( debug ) { logger . debug ( "Retaining elements: " + retainList ) ; } collection . clear ( ) ; collection . addAll ( retainList ) ; return filterTarget ; } if ( filterTarget . getClass ( ) . isArray ( ) ) { Object [ ] array = ( Object [ ] ) filterTarget ; retainList = new ArrayList ( array . length ) ; if ( debug ) { logger . debug ( "Filtering array with " + array . length + " elements" ) ; } if ( permissionCacheOptimizer != null ) { permissionCacheOptimizer . cachePermissionsFor ( rootObject . getAuthentication ( ) , Arrays . asList ( array ) ) ; } for ( Object o : array ) { rootObject . setFilterObject ( o ) ; if ( ExpressionUtils . evaluateAsBoolean ( filterExpression , ctx ) ) { retainList . add ( o ) ; } } if ( debug ) { logger . debug ( "Retaining elements: " + retainList ) ; } Object [ ] filtered = ( Object [ ] ) Array . newInstance ( filterTarget . getClass ( ) . getComponentType ( ) , retainList . size ( ) ) ; for ( int i = 0 ; i < retainList . size ( ) ; i ++ ) { filtered [ i ] = retainList . get ( i ) ; } return filtered ; } if ( filterTarget instanceof Stream ) { final Stream < ? > original = ( Stream < ? > ) filterTarget ; return original . filter ( filterObject -> { rootObject . setFilterObject ( filterObject ) ; return ExpressionUtils . evaluateAsBoolean ( filterExpression , ctx ) ; } ) . onClose ( original :: close ) ; } throw new IllegalArgumentException ( "Filter target must be a collection, array, or stream type, but was " + filterTarget ) ;


signature:
public class ReactiveRemoteJWKSource { /** * Updates the cached JWK set from the configured URL .
 * @ return The updated JWK set .
 * @ throws RemoteKeySourceException If JWK retrieval failed . */
private Mono < JWKSet > getJWKSet ( ) { } }

implementation: return this . webClient . get ( ) . uri ( this . jwkSetURL ) . retrieve ( ) . bodyToMono ( String . class ) . map ( this :: parse ) . doOnNext ( jwkSet -> this . cachedJWKSet . set ( Mono . just ( jwkSet ) ) ) . cache ( ) ;


signature:
public class ReactiveRemoteJWKSource { /** * Returns the first specified key ID ( kid ) for a JWK matcher .
 * @ param jwkMatcher The JWK matcher . Must not be { @ code null } .
 * @ return The first key ID , { @ code null } if none . */
protected static String getFirstSpecifiedKeyID ( final JWKMatcher jwkMatcher ) { } }

implementation: Set < String > keyIDs = jwkMatcher . getKeyIDs ( ) ; if ( keyIDs == null || keyIDs . isEmpty ( ) ) { return null ; } for ( String id : keyIDs ) { if ( id != null ) { return id ; } } return null ; // No kid in matcher


signature:
public class DefaultRedirectStrategy { /** * Redirects the response to the supplied URL .
 * If < tt > contextRelative < / tt > is set , the redirect value will be the value after the
 * request context path . Note that this will result in the loss of protocol
 * information ( HTTP or HTTPS ) , so will cause problems if a redirect is being
 * performed to change to HTTPS , for example . */
public void sendRedirect ( HttpServletRequest request , HttpServletResponse response , String url ) throws IOException { } }

implementation: String redirectUrl = calculateRedirectUrl ( request . getContextPath ( ) , url ) ; redirectUrl = response . encodeRedirectURL ( redirectUrl ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Redirecting to '" + redirectUrl + "'" ) ; } response . sendRedirect ( redirectUrl ) ;


signature:
public class OpenIDAuthenticationProvider { /** * ( non - Javadoc )
 * @ see
 * org . springframework . security . authentication . AuthenticationProvider # authenticate
 * ( org . springframework . security . Authentication ) */
public Authentication authenticate ( final Authentication authentication ) throws AuthenticationException { } }

implementation:
if ( ! supports ( authentication . getClass ( ) ) ) { return null ; } if ( authentication instanceof OpenIDAuthenticationToken ) { OpenIDAuthenticationToken response = ( OpenIDAuthenticationToken ) authentication ; OpenIDAuthenticationStatus status = response . getStatus ( ) ; // handle the various possibilities
if ( status == OpenIDAuthenticationStatus . SUCCESS ) { // Lookup user details
UserDetails userDetails = this . userDetailsService . loadUserDetails ( response ) ; return createSuccessfulAuthentication ( userDetails , response ) ; } else if ( status == OpenIDAuthenticationStatus . CANCELLED ) { throw new AuthenticationCancelledException ( "Log in cancelled" ) ; } else if ( status == OpenIDAuthenticationStatus . ERROR ) { throw new AuthenticationServiceException ( "Error message from server: " + response . getMessage ( ) ) ; } else if ( status == OpenIDAuthenticationStatus . FAILURE ) { throw new BadCredentialsException ( "Log in failed - identity could not be verified" ) ; } else if ( status == OpenIDAuthenticationStatus . SETUP_NEEDED ) { throw new AuthenticationServiceException ( "The server responded setup was needed, which shouldn't happen" ) ; } else { throw new AuthenticationServiceException ( "Unrecognized return value " + status . toString ( ) ) ; } } return null ;


signature:
public class OpenIDAuthenticationProvider { /** * Handles the creation of the final < tt > Authentication < / tt > object which will be
 * returned by the provider .
 * The default implementation just creates a new OpenIDAuthenticationToken from the
 * original , but with the UserDetails as the principal and including the authorities
 * loaded by the UserDetailsService .
 * @ param userDetails the loaded UserDetails object
 * @ param auth the token passed to the authenticate method , containing
 * @ return the token which will represent the authenticated user . */
protected Authentication createSuccessfulAuthentication ( UserDetails userDetails , OpenIDAuthenticationToken auth ) { } }

implementation: return new OpenIDAuthenticationToken ( userDetails , this . authoritiesMapper . mapAuthorities ( userDetails . getAuthorities ( ) ) , auth . getIdentityUrl ( ) , auth . getAttributes ( ) ) ;


signature:
public class Jsr250Voter { /** * Votes according to JSR 250.
 * If no JSR - 250 attributes are found , it will abstain , otherwise it will grant or
 * deny access based on the attributes that are found .
 * @ param authentication The authentication object .
 * @ param object The access object .
 * @ param definition The configuration definition .
 * @ return The vote . */
public int vote ( Authentication authentication , Object object , Collection < ConfigAttribute > definition ) { } }

implementation:
boolean jsr250AttributeFound = false ; for ( ConfigAttribute attribute : definition ) { if ( Jsr250SecurityConfig . PERMIT_ALL_ATTRIBUTE . equals ( attribute ) ) { return ACCESS_GRANTED ; } if ( Jsr250SecurityConfig . DENY_ALL_ATTRIBUTE . equals ( attribute ) ) { return ACCESS_DENIED ; } if ( supports ( attribute ) ) { jsr250AttributeFound = true ; // Attempt to find a matching granted authority
for ( GrantedAuthority authority : authentication . getAuthorities ( ) ) { if ( attribute . getAttribute ( ) . equals ( authority . getAuthority ( ) ) ) { return ACCESS_GRANTED ; } } } } return jsr250AttributeFound ? ACCESS_DENIED : ACCESS_ABSTAIN ;


signature: public class OpenIDAuthenticationFilter { @ Override public void afterPropertiesSet ( ) { } }

implementation: super . afterPropertiesSet ( ) ; if ( consumer == null ) { try { consumer = new OpenID4JavaConsumer ( ) ; } catch ( ConsumerException e ) { throw new IllegalArgumentException ( "Failed to initialize OpenID" , e ) ; } } if ( returnToUrlParameters . isEmpty ( ) && getRememberMeServices ( ) instanceof AbstractRememberMeServices ) { returnToUrlParameters = new HashSet < > ( ) ; returnToUrlParameters . add ( ( ( AbstractRememberMeServices ) getRememberMeServices ( ) ) . getParameter ( ) ) ; }


signature:
public class OpenIDAuthenticationFilter { /** * Authentication has two phases .
 * < ol >
 * < li > The initial submission of the claimed OpenID . A redirect to the URL returned
 * from the consumer will be performed and null will be returned . < / li >
 * < li > The redirection from the OpenID server to the return _ to URL , once it has
 * authenticated the user < / li >
 * < / ol > */
@ Override public Authentication attemptAuthentication ( HttpServletRequest request , HttpServletResponse response ) throws AuthenticationException , IOException { } }

implementation:
OpenIDAuthenticationToken token ; String identity = request . getParameter ( "openid.identity" ) ; if ( ! StringUtils . hasText ( identity ) ) { String claimedIdentity = obtainUsername ( request ) ; try { String returnToUrl = buildReturnToUrl ( request ) ; String realm = lookupRealm ( returnToUrl ) ; String openIdUrl = consumer . beginConsumption ( request , claimedIdentity , returnToUrl , realm ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "return_to is '" + returnToUrl + "', realm is '" + realm + "'" ) ; logger . debug ( "Redirecting to " + openIdUrl ) ; } response . sendRedirect ( openIdUrl ) ; // Indicate to parent class that authentication is continuing .
return null ; } catch ( OpenIDConsumerException e ) { logger . debug ( "Failed to consume claimedIdentity: " + claimedIdentity , e ) ; throw new AuthenticationServiceException ( "Unable to process claimed identity '" + claimedIdentity + "'" ) ; } } if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Supplied OpenID identity is " + identity ) ; } try { token = consumer . endConsumption ( request ) ; } catch ( OpenIDConsumerException oice ) { throw new AuthenticationServiceException ( "Consumer error" , oice ) ; } token . setDetails ( authenticationDetailsSource . buildDetails ( request ) ) ; // delegate to the authentication provider
Authentication authentication = this . getAuthenticationManager ( ) . authenticate ( token ) ; return authentication ;


signature:
public class OpenIDAuthenticationFilter { /** * Builds the < tt > return _ to < / tt > URL that will be sent to the OpenID service provider .
 * By default returns the URL of the current request .
 * @ param request the current request which is being processed by this filter
 * @ return The < tt > return _ to < / tt > URL . */
protected String buildReturnToUrl ( HttpServletRequest request ) { } }

implementation:
StringBuffer sb = request . getRequestURL ( ) ; Iterator < String > iterator = returnToUrlParameters . iterator ( ) ; boolean isFirst = true ; while ( iterator . hasNext ( ) ) { String name = iterator . next ( ) ; // Assume for simplicity that there is only one value
String value = request . getParameter ( name ) ; if ( value == null ) { continue ; } if ( isFirst ) { sb . append ( "?" ) ; isFirst = false ; } sb . append ( utf8UrlEncode ( name ) ) . append ( "=" ) . append ( utf8UrlEncode ( value ) ) ; if ( iterator . hasNext ( ) ) { sb . append ( "&" ) ; } } return sb . toString ( ) ;


signature:
public class OpenIDAuthenticationFilter { /** * Reads the < tt > claimedIdentityFieldName < / tt > from the submitted request . */
protected String obtainUsername ( HttpServletRequest req ) { } }

implementation: String claimedIdentity = req . getParameter ( claimedIdentityFieldName ) ; if ( ! StringUtils . hasText ( claimedIdentity ) ) { logger . error ( "No claimed identity supplied in authentication request" ) ; return "" ; } return claimedIdentity . trim ( ) ;


signature:
public class OpenIDAuthenticationFilter { /** * Performs URL encoding with UTF - 8
 * @ param value the value to URL encode
 * @ return the encoded value */
private String utf8UrlEncode ( String value ) { } }

implementation: try { return URLEncoder . encode ( value , "UTF-8" ) ; } catch ( UnsupportedEncodingException e ) { Error err = new AssertionError ( "The Java platform guarantees UTF-8 support, but it seemingly is not present." ) ; err . initCause ( e ) ; throw err ; }


signature: public class SpringCacheBasedUserCache { public UserDetails getUserFromCache ( String username ) { } }

implementation: Cache . ValueWrapper element = username != null ? cache . get ( username ) : null ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Cache hit: " + ( element != null ) + "; username: " + username ) ; } if ( element == null ) { return null ; } else { return ( UserDetails ) element . get ( ) ; }


signature:
public class SecurityContextHolderAwareRequestWrapper { /** * Obtain the current active < code > Authentication < / code >
 * @ return the authentication object or < code > null < / code > */
private Authentication getAuthentication ( ) { } }

implementation: Authentication auth = SecurityContextHolder . getContext ( ) . getAuthentication ( ) ; if ( ! trustResolver . isAnonymous ( auth ) ) { return auth ; } return null ;


signature:
public class SecurityContextHolderAwareRequestWrapper { /** * Returns the principal ' s name , as obtained from the
 * < code > SecurityContextHolder < / code > . Properly handles both < code > String < / code > - based
 * and < code > UserDetails < / code > - based principals .
 * @ return the username or < code > null < / code > if unavailable */
@ Override public String getRemoteUser ( ) { } }

implementation: Authentication auth = getAuthentication ( ) ; if ( ( auth == null ) || ( auth . getPrincipal ( ) == null ) ) { return null ; } if ( auth . getPrincipal ( ) instanceof UserDetails ) { return ( ( UserDetails ) auth . getPrincipal ( ) ) . getUsername ( ) ; } return auth . getPrincipal ( ) . toString ( ) ;


signature:
public class SecurityContextHolderAwareRequestWrapper { /** * Returns the < code > Authentication < / code > ( which is a subclass of
 * < code > Principal < / code > ) , or < code > null < / code > if unavailable .
 * @ return the < code > Authentication < / code > , or < code > null < / code > */
@ Override public Principal getUserPrincipal ( ) { } }

implementation: Authentication auth = getAuthentication ( ) ; if ( ( auth == null ) || ( auth . getPrincipal ( ) == null ) ) { return null ; } return auth ;


signature:
public class LdapAuthenticationProviderConfigurer { /** * Gets the { @ link LdapAuthoritiesPopulator } and defaults to
 * { @ link DefaultLdapAuthoritiesPopulator }
 * @ return the { @ link LdapAuthoritiesPopulator } */
private LdapAuthoritiesPopulator getLdapAuthoritiesPopulator ( ) { } }

implementation: if ( ldapAuthoritiesPopulator != null ) { return ldapAuthoritiesPopulator ; } DefaultLdapAuthoritiesPopulator defaultAuthoritiesPopulator = new DefaultLdapAuthoritiesPopulator ( contextSource , groupSearchBase ) ; defaultAuthoritiesPopulator . setGroupRoleAttribute ( groupRoleAttribute ) ; defaultAuthoritiesPopulator . setGroupSearchFilter ( groupSearchFilter ) ; defaultAuthoritiesPopulator . setRolePrefix ( this . rolePrefix ) ; this . ldapAuthoritiesPopulator = defaultAuthoritiesPopulator ; return defaultAuthoritiesPopulator ;


signature:
public class LdapAuthenticationProviderConfigurer { /** * Gets the { @ link GrantedAuthoritiesMapper } and defaults to { @ link SimpleAuthorityMapper } .
 * @ return the { @ link GrantedAuthoritiesMapper }
 * @ throws Exception if errors in { @ link SimpleAuthorityMapper # afterPropertiesSet ( ) } */
protected GrantedAuthoritiesMapper getAuthoritiesMapper ( ) throws Exception { } }

implementation: if ( authoritiesMapper != null ) { return authoritiesMapper ; } SimpleAuthorityMapper simpleAuthorityMapper = new SimpleAuthorityMapper ( ) ; simpleAuthorityMapper . setPrefix ( this . rolePrefix ) ; simpleAuthorityMapper . afterPropertiesSet ( ) ; this . authoritiesMapper = simpleAuthorityMapper ; return simpleAuthorityMapper ;


signature:
public class LdapAuthenticationProviderConfigurer { /** * Creates the { @ link LdapAuthenticator } to use
 * @ param contextSource the { @ link BaseLdapPathContextSource } to use
 * @ return the { @ link LdapAuthenticator } to use */
private LdapAuthenticator createLdapAuthenticator ( BaseLdapPathContextSource contextSource ) { } }

implementation: AbstractLdapAuthenticator ldapAuthenticator = passwordEncoder == null ? createBindAuthenticator ( contextSource ) : createPasswordCompareAuthenticator ( contextSource ) ; LdapUserSearch userSearch = createUserSearch ( ) ; if ( userSearch != null ) { ldapAuthenticator . setUserSearch ( userSearch ) ; } if ( userDnPatterns != null && userDnPatterns . length > 0 ) { ldapAuthenticator . setUserDnPatterns ( userDnPatterns ) ; } return postProcess ( ldapAuthenticator ) ;


signature:
public class LdapAuthenticationProviderConfigurer { /** * Creates { @ link PasswordComparisonAuthenticator }
 * @ param contextSource the { @ link BaseLdapPathContextSource } to use
 * @ return */
private PasswordComparisonAuthenticator createPasswordCompareAuthenticator ( BaseLdapPathContextSource contextSource ) { } }

implementation: PasswordComparisonAuthenticator ldapAuthenticator = new PasswordComparisonAuthenticator ( contextSource ) ; if ( passwordAttribute != null ) { ldapAuthenticator . setPasswordAttributeName ( passwordAttribute ) ; } ldapAuthenticator . setPasswordEncoder ( passwordEncoder ) ; return ldapAuthenticator ;


signature:
public class LdapAuthenticationProviderConfigurer { /** * Specifies the { @ link org . springframework . security . crypto . password . PasswordEncoder }
 * to be used when authenticating with password comparison .
 * @ param passwordEncoder the
 * { @ link org . springframework . security . crypto . password . PasswordEncoder } to use
 * @ return the { @ link LdapAuthenticationProviderConfigurer } for further customization */
public LdapAuthenticationProviderConfigurer < B > passwordEncoder ( final org . springframework . security . crypto . password . PasswordEncoder passwordEncoder ) { } }

implementation: Assert . notNull ( passwordEncoder , "passwordEncoder must not be null." ) ; this . passwordEncoder = passwordEncoder ; return this ;


signature:
public class DefaultClientCredentialsTokenResponseClient { /** * Sets the { @ link Converter } used for converting the { @ link OAuth2ClientCredentialsGrantRequest }
 * to a { @ link RequestEntity } representation of the OAuth 2.0 Access Token Request .
 * @ param requestEntityConverter the { @ link Converter } used for converting to a { @ link RequestEntity } representation of the Access Token Request */
public void setRequestEntityConverter ( Converter < OAuth2ClientCredentialsGrantRequest , RequestEntity < ? > > requestEntityConverter ) { } }

implementation: Assert . notNull ( requestEntityConverter , "requestEntityConverter cannot be null" ) ; this . requestEntityConverter = requestEntityConverter ;


signature:
public class OidcClientInitiatedServerLogoutSuccessHandler { /** * { @ inheritDoc } */
@ Override public Mono < Void > onLogoutSuccess ( WebFilterExchange exchange , Authentication authentication ) { } }

implementation: return Mono . just ( authentication ) . filter ( OAuth2AuthenticationToken . class :: isInstance ) . filter ( token -> authentication . getPrincipal ( ) instanceof OidcUser ) . map ( OAuth2AuthenticationToken . class :: cast ) . flatMap ( this :: endSessionEndpoint ) . map ( endSessionEndpoint -> endpointUri ( endSessionEndpoint , authentication ) ) . switchIfEmpty ( this . serverLogoutSuccessHandler . onLogoutSuccess ( exchange , authentication ) . then ( Mono . empty ( ) ) ) . flatMap ( endpointUri -> this . redirectStrategy . sendRedirect ( exchange . getExchange ( ) , endpointUri ) ) ;


signature: public class AbstractRetryEntryPoint { public void commence ( HttpServletRequest request , HttpServletResponse response ) throws IOException , ServletException { } }

implementation: String queryString = request . getQueryString ( ) ; String redirectUrl = request . getRequestURI ( ) + ( ( queryString == null ) ? "" : ( "?" + queryString ) ) ; Integer currentPort = Integer . valueOf ( portResolver . getServerPort ( request ) ) ; Integer redirectPort = getMappedPort ( currentPort ) ; if ( redirectPort != null ) { boolean includePort = redirectPort . intValue ( ) != standardPort ; redirectUrl = scheme + request . getServerName ( ) + ( ( includePort ) ? ( ":" + redirectPort ) : "" ) + redirectUrl ; } if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Redirecting to: " + redirectUrl ) ; } redirectStrategy . sendRedirect ( request , response , redirectUrl ) ;


signature:
public class OAuth2AccessTokenResponseHttpMessageConverter { /** * Sets the { @ link Converter } used for converting the OAuth 2.0 Access Token Response parameters
 * to an { @ link OAuth2AccessTokenResponse } .
 * @ param tokenResponseConverter the { @ link Converter } used for converting to an { @ link OAuth2AccessTokenResponse } */
public final void setTokenResponseConverter ( Converter < Map < String , String > , OAuth2AccessTokenResponse > tokenResponseConverter ) { } }

implementation: Assert . notNull ( tokenResponseConverter , "tokenResponseConverter cannot be null" ) ; this . tokenResponseConverter = tokenResponseConverter ;


signature:
public class OAuth2AccessTokenResponseHttpMessageConverter { /** * Sets the { @ link Converter } used for converting the { @ link OAuth2AccessTokenResponse }
 * to a { @ code Map } representation of the OAuth 2.0 Access Token Response parameters .
 * @ param tokenResponseParametersConverter the { @ link Converter } used for converting to a { @ code Map } representation of the Access Token Response parameters */
public final void setTokenResponseParametersConverter ( Converter < OAuth2AccessTokenResponse , Map < String , String > > tokenResponseParametersConverter ) { } }

implementation: Assert . notNull ( tokenResponseParametersConverter , "tokenResponseParametersConverter cannot be null" ) ; this . tokenResponseParametersConverter = tokenResponseParametersConverter ;


signature:
public class WebSpherePreAuthenticatedWebAuthenticationDetailsSource { /** * Get a list of Granted Authorities based on the current user ' s WebSphere groups .
 * @ return authorities mapped from the user ' s WebSphere groups . */
private Collection < ? extends GrantedAuthority > getWebSphereGroupsBasedGrantedAuthorities ( ) { } }

implementation: List < String > webSphereGroups = wasHelper . getGroupsForCurrentUser ( ) ; Collection < ? extends GrantedAuthority > userGas = webSphereGroups2GrantedAuthoritiesMapper . getGrantedAuthorities ( webSphereGroups ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "WebSphere groups: " + webSphereGroups + " mapped to Granted Authorities: " + userGas ) ; } return userGas ;


signature:
public class PasswordPolicyControlFactory { /** * Creates an instance of PasswordPolicyResponseControl if the passed control is a
 * response control of this type . Attributes of the result are filled with the correct
 * values ( e . g . error code ) .
 * @ param ctl the control the check
 * @ return a response control of type PasswordPolicyResponseControl , or null */
public Control getControlInstance ( Control ctl ) { } }

implementation: if ( ctl . getID ( ) . equals ( PasswordPolicyControl . OID ) ) { return new PasswordPolicyResponseControl ( ctl . getEncodedValue ( ) ) ; } return null ;


signature: public class CasAuthenticationProvider { public void afterPropertiesSet ( ) throws Exception { } }

implementation: Assert . notNull ( this . authenticationUserDetailsService , "An authenticationUserDetailsService must be set" ) ; Assert . notNull ( this . ticketValidator , "A ticketValidator must be set" ) ; Assert . notNull ( this . statelessTicketCache , "A statelessTicketCache must be set" ) ; Assert . hasText ( this . key , "A Key is required so CasAuthenticationProvider can identify tokens it previously authenticated" ) ; Assert . notNull ( this . messages , "A message source must be set" ) ;


signature:
public class CasAuthenticationProvider { /** * Gets the serviceUrl . If the { @ link Authentication # getDetails ( ) } is an instance of
 * { @ link ServiceAuthenticationDetails } , then
 * { @ link ServiceAuthenticationDetails # getServiceUrl ( ) } is used . Otherwise , the
 * { @ link ServiceProperties # getService ( ) } is used .
 * @ param authentication
 * @ return */
private String getServiceUrl ( Authentication authentication ) { } }

implementation: String serviceUrl ; if ( authentication . getDetails ( ) instanceof ServiceAuthenticationDetails ) { serviceUrl = ( ( ServiceAuthenticationDetails ) authentication . getDetails ( ) ) . getServiceUrl ( ) ; } else if ( serviceProperties == null ) { throw new IllegalStateException ( "serviceProperties cannot be null unless Authentication.getDetails() implements ServiceAuthenticationDetails." ) ; } else if ( serviceProperties . getService ( ) == null ) { throw new IllegalStateException ( "serviceProperties.getService() cannot be null unless Authentication.getDetails() implements ServiceAuthenticationDetails." ) ; } else { serviceUrl = serviceProperties . getService ( ) ; } if ( logger . isDebugEnabled ( ) ) { logger . debug ( "serviceUrl = " + serviceUrl ) ; } return serviceUrl ;


signature:
public class CasAuthenticationProvider { /** * Template method for retrieving the UserDetails based on the assertion . Default is
 * to call configured userDetailsService and pass the username . Deployers can override
 * this method and retrieve the user based on any criteria they desire .
 * @ param assertion The CAS Assertion .
 * @ return the UserDetails . */
protected UserDetails loadUserByAssertion ( final Assertion assertion ) { } }

implementation: final CasAssertionAuthenticationToken token = new CasAssertionAuthenticationToken ( assertion , "" ) ; return this . authenticationUserDetailsService . loadUserDetails ( token ) ;


signature:
public class OAuth2ClientConfigurer { /** * Sets the repository of client registrations .
 * @ param clientRegistrationRepository the repository of client registrations
 * @ return the { @ link OAuth2ClientConfigurer } for further configuration */
public OAuth2ClientConfigurer < B > clientRegistrationRepository ( ClientRegistrationRepository clientRegistrationRepository ) { } }

implementation: Assert . notNull ( clientRegistrationRepository , "clientRegistrationRepository cannot be null" ) ; this . getBuilder ( ) . setSharedObject ( ClientRegistrationRepository . class , clientRegistrationRepository ) ; return this ;


signature:
public class OAuth2ClientConfigurer { /** * Sets the repository for authorized client ( s ) .
 * @ param authorizedClientRepository the authorized client repository
 * @ return the { @ link OAuth2ClientConfigurer } for further configuration */
public OAuth2ClientConfigurer < B > authorizedClientRepository ( OAuth2AuthorizedClientRepository authorizedClientRepository ) { } }

implementation: Assert . notNull ( authorizedClientRepository , "authorizedClientRepository cannot be null" ) ; this . getBuilder ( ) . setSharedObject ( OAuth2AuthorizedClientRepository . class , authorizedClientRepository ) ; return this ;


signature:
public class OAuth2ClientConfigurer { /** * Sets the service for authorized client ( s ) .
 * @ param authorizedClientService the authorized client service
 * @ return the { @ link OAuth2ClientConfigurer } for further configuration */
public OAuth2ClientConfigurer < B > authorizedClientService ( OAuth2AuthorizedClientService authorizedClientService ) { } }

implementation: Assert . notNull ( authorizedClientService , "authorizedClientService cannot be null" ) ; this . authorizedClientRepository ( new AuthenticatedPrincipalOAuth2AuthorizedClientRepository ( authorizedClientService ) ) ; return this ;


signature:
public class MockWebServerPropertySource { /** * Get ' s the URL ( i . e . " http : / / localhost : 123456 " )
 * @ return */
private String getUrl ( ) { } }

implementation: MockWebServer mockWebServer = getSource ( ) ; if ( ! this . started ) { intializeMockWebServer ( mockWebServer ) ; } String url = mockWebServer . url ( "" ) . url ( ) . toExternalForm ( ) ; return url . substring ( 0 , url . length ( ) - 1 ) ;


signature:
public class WebSpherePreAuthenticatedProcessingFilter { /** * Return the WebSphere user name . */
protected Object getPreAuthenticatedPrincipal ( HttpServletRequest httpRequest ) { } }

implementation: Object principal = wasHelper . getCurrentUserName ( ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "PreAuthenticated WebSphere principal: " + principal ) ; } return principal ;


signature:
public class CustomUserDetailsService { /** * Implementation of { @ code UserDetailsService } . We only need this to satisfy the
 * { @ code RememberMeServices } requirements . */
public UserDetails loadUserByUsername ( String id ) throws UsernameNotFoundException { } }

implementation: UserDetails user = registeredUsers . get ( id ) ; if ( user == null ) { throw new UsernameNotFoundException ( id ) ; } return user ;


signature:
public class CustomUserDetailsService { /** * Implementation of { @ code AuthenticationUserDetailsService } which allows full access
 * to the submitted { @ code Authentication } object . Used by the
 * OpenIDAuthenticationProvider . */
public UserDetails loadUserDetails ( OpenIDAuthenticationToken token ) { } }

implementation: String id = token . getIdentityUrl ( ) ; CustomUserDetails user = registeredUsers . get ( id ) ; if ( user != null ) { return user ; } String email = null ; String firstName = null ; String lastName = null ; String fullName = null ; List < OpenIDAttribute > attributes = token . getAttributes ( ) ; for ( OpenIDAttribute attribute : attributes ) { if ( attribute . getName ( ) . equals ( "email" ) ) { email = attribute . getValues ( ) . get ( 0 ) ; } if ( attribute . getName ( ) . equals ( "firstname" ) ) { firstName = attribute . getValues ( ) . get ( 0 ) ; } if ( attribute . getName ( ) . equals ( "lastname" ) ) { lastName = attribute . getValues ( ) . get ( 0 ) ; } if ( attribute . getName ( ) . equals ( "fullname" ) ) { fullName = attribute . getValues ( ) . get ( 0 ) ; } } if ( fullName == null ) { StringBuilder fullNameBldr = new StringBuilder ( ) ; if ( firstName != null ) { fullNameBldr . append ( firstName ) ; } if ( lastName != null ) { fullNameBldr . append ( " " ) . append ( lastName ) ; } fullName = fullNameBldr . toString ( ) ; } user = new CustomUserDetails ( id , DEFAULT_AUTHORITIES ) ; user . setEmail ( email ) ; user . setName ( fullName ) ; registeredUsers . put ( id , user ) ; user = new CustomUserDetails ( id , DEFAULT_AUTHORITIES ) ; user . setEmail ( email ) ; user . setName ( fullName ) ; user . setNewUser ( true ) ; return user ;


signature:
public class ServletOAuth2AuthorizedClientExchangeFilterFunction { /** * Provides defaults for the { @ link HttpServletRequest } and the { @ link HttpServletResponse } using
 * { @ link RequestContextHolder } . It also provides defaults for the { @ link Authentication } using
 * { @ link SecurityContextHolder } . It also can default the { @ link OAuth2AuthorizedClient } using the
 * { @ link # clientRegistrationId ( String ) } or the { @ link # authentication ( Authentication ) } .
 * @ return the { @ link Consumer } to populate the attributes */
public Consumer < WebClient . RequestHeadersSpec < ? > > defaultRequest ( ) { } }

implementation: return spec -> { spec . attributes ( attrs -> { populateDefaultRequestResponse ( attrs ) ; populateDefaultAuthentication ( attrs ) ; populateDefaultOAuth2AuthorizedClient ( attrs ) ; } ) ; } ;


signature:
public class ServletOAuth2AuthorizedClientExchangeFilterFunction { /** * Modifies the { @ link ClientRequest # attributes ( ) } to include the { @ link OAuth2AuthorizedClient } to be used for
 * providing the Bearer Token .
 * @ param authorizedClient the { @ link OAuth2AuthorizedClient } to use .
 * @ return the { @ link Consumer } to populate the attributes */
public static Consumer < Map < String , Object > > oauth2AuthorizedClient ( OAuth2AuthorizedClient authorizedClient ) { } }

implementation: return attributes -> { if ( authorizedClient == null ) { attributes . remove ( OAUTH2_AUTHORIZED_CLIENT_ATTR_NAME ) ; } else { attributes . put ( OAUTH2_AUTHORIZED_CLIENT_ATTR_NAME , authorizedClient ) ; } } ;


signature:
public class ServletOAuth2AuthorizedClientExchangeFilterFunction { /** * Modifies the { @ link ClientRequest # attributes ( ) } to include the { @ link ClientRegistration # getRegistrationId ( ) } to
 * be used to look up the { @ link OAuth2AuthorizedClient } .
 * @ param clientRegistrationId the { @ link ClientRegistration # getRegistrationId ( ) } to
 * be used to look up the { @ link OAuth2AuthorizedClient } .
 * @ return the { @ link Consumer } to populate the attributes */
public static Consumer < Map < String , Object > > clientRegistrationId ( String clientRegistrationId ) { } }

implementation: return attributes -> attributes . put ( CLIENT_REGISTRATION_ID_ATTR_NAME , clientRegistrationId ) ;


signature:
public class ServletOAuth2AuthorizedClientExchangeFilterFunction { /** * Modifies the { @ link ClientRequest # attributes ( ) } to include the { @ link Authentication } used to
 * look up and save the { @ link OAuth2AuthorizedClient } . The value is defaulted in
 * { @ link ServletOAuth2AuthorizedClientExchangeFilterFunction # defaultRequest ( ) }
 * @ param authentication the { @ link Authentication } to use .
 * @ return the { @ link Consumer } to populate the attributes */
public static Consumer < Map < String , Object > > authentication ( Authentication authentication ) { } }

implementation: return attributes -> attributes . put ( AUTHENTICATION_ATTR_NAME , authentication ) ;


signature:
public class ServletOAuth2AuthorizedClientExchangeFilterFunction { /** * Modifies the { @ link ClientRequest # attributes ( ) } to include the { @ link HttpServletRequest } used to
 * look up and save the { @ link OAuth2AuthorizedClient } . The value is defaulted in
 * { @ link ServletOAuth2AuthorizedClientExchangeFilterFunction # defaultRequest ( ) }
 * @ param request the { @ link HttpServletRequest } to use .
 * @ return the { @ link Consumer } to populate the attributes */
public static Consumer < Map < String , Object > > httpServletRequest ( HttpServletRequest request ) { } }

implementation: return attributes -> attributes . put ( HTTP_SERVLET_REQUEST_ATTR_NAME , request ) ;


signature:
public class ServletOAuth2AuthorizedClientExchangeFilterFunction { /** * Modifies the { @ link ClientRequest # attributes ( ) } to include the { @ link HttpServletResponse } used to
 * save the { @ link OAuth2AuthorizedClient } . The value is defaulted in
 * { @ link ServletOAuth2AuthorizedClientExchangeFilterFunction # defaultRequest ( ) }
 * @ param response the { @ link HttpServletResponse } to use .
 * @ return the { @ link Consumer } to populate the attributes */
public static Consumer < Map < String , Object > > httpServletResponse ( HttpServletResponse response ) { } }

implementation: return attributes -> attributes . put ( HTTP_SERVLET_RESPONSE_ATTR_NAME , response ) ;


signature:
public class AclPermissionEvaluator { /** * Determines whether the user has the given permission ( s ) on the domain object using
 * the ACL configuration . If the domain object is null , returns false ( this can always
 * be overridden using a null check in the expression itself ) . */
public boolean hasPermission ( Authentication authentication , Object domainObject , Object permission ) { } }

implementation: if ( domainObject == null ) { return false ; } ObjectIdentity objectIdentity = objectIdentityRetrievalStrategy . getObjectIdentity ( domainObject ) ; return checkPermission ( authentication , objectIdentity , permission ) ;


signature: public class TokenBasedRememberMeServices { @ Override protected UserDetails processAutoLoginCookie ( String [ ] cookieTokens , HttpServletRequest request , HttpServletResponse response ) { } }

implementation:
if ( cookieTokens . length != 3 ) { throw new InvalidCookieException ( "Cookie token did not contain 3" + " tokens, but contained '" + Arrays . asList ( cookieTokens ) + "'" ) ; } long tokenExpiryTime ; try { tokenExpiryTime = new Long ( cookieTokens [ 1 ] ) . longValue ( ) ; } catch ( NumberFormatException nfe ) { throw new InvalidCookieException ( "Cookie token[1] did not contain a valid number (contained '" + cookieTokens [ 1 ] + "')" ) ; } if ( isTokenExpired ( tokenExpiryTime ) ) { throw new InvalidCookieException ( "Cookie token[1] has expired (expired on '" + new Date ( tokenExpiryTime ) + "'; current time is '" + new Date ( ) + "')" ) ; } // Check the user exists .
// Defer lookup until after expiry time checked , to possibly avoid expensive
// database call .
UserDetails userDetails = getUserDetailsService ( ) . loadUserByUsername ( cookieTokens [ 0 ] ) ; // Check signature of token matches remaining details .
// Must do this after user lookup , as we need the DAO - derived password .
// If efficiency was a major issue , just add in a UserCache implementation ,
// but recall that this method is usually only called once per HttpSession - if
// the token is valid ,
// it will cause SecurityContextHolder population , whilst if invalid , will cause
// the cookie to be cancelled .
String expectedTokenSignature = makeTokenSignature ( tokenExpiryTime , userDetails . getUsername ( ) , userDetails . getPassword ( ) ) ; if ( ! equals ( expectedTokenSignature , cookieTokens [ 2 ] ) ) { throw new InvalidCookieException ( "Cookie token[2] contained signature '" + cookieTokens [ 2 ] + "' but expected '" + expectedTokenSignature + "'" ) ; } return userDetails ;


signature:
public class TokenBasedRememberMeServices { /** * Calculates the digital signature to be put in the cookie . Default value is MD5
 * ( " username : tokenExpiryTime : password : key " ) */
protected String makeTokenSignature ( long tokenExpiryTime , String username , String password ) { } }

implementation: String data = username + ":" + tokenExpiryTime + ":" + password + ":" + getKey ( ) ; MessageDigest digest ; try { digest = MessageDigest . getInstance ( "MD5" ) ; } catch ( NoSuchAlgorithmException e ) { throw new IllegalStateException ( "No MD5 algorithm available!" ) ; } return new String ( Hex . encode ( digest . digest ( data . getBytes ( ) ) ) ) ;


signature:
public class EncodingUtils { /** * Combine the individual byte arrays into one array . */
public static byte [ ] concatenate ( byte [ ] ... arrays ) { } }

implementation: int length = 0 ; for ( byte [ ] array : arrays ) { length += array . length ; } byte [ ] newArray = new byte [ length ] ; int destPos = 0 ; for ( byte [ ] array : arrays ) { System . arraycopy ( array , 0 , newArray , destPos , array . length ) ; destPos += array . length ; } return newArray ;


signature:
public class EncodingUtils { /** * Extract a sub array of bytes out of the byte array .
 * @ param array the byte array to extract from
 * @ param beginIndex the beginning index of the sub array , inclusive
 * @ param endIndex the ending index of the sub array , exclusive */
public static byte [ ] subArray ( byte [ ] array , int beginIndex , int endIndex ) { } }

implementation: int length = endIndex - beginIndex ; byte [ ] subarray = new byte [ length ] ; System . arraycopy ( array , beginIndex , subarray , 0 , length ) ; return subarray ;


signature:
public class MapBasedAttributes2GrantedAuthoritiesMapper { /** * Map the given array of attributes to Spring Security GrantedAuthorities . */
public List < GrantedAuthority > getGrantedAuthorities ( Collection < String > attributes ) { } }

implementation: ArrayList < GrantedAuthority > gaList = new ArrayList < > ( ) ; for ( String attribute : attributes ) { Collection < GrantedAuthority > c = attributes2grantedAuthoritiesMap . get ( attribute ) ; if ( c != null ) { gaList . addAll ( c ) ; } } gaList . trimToSize ( ) ; return gaList ;


signature:
public class MapBasedAttributes2GrantedAuthoritiesMapper { /** * Preprocess the given map to convert all the values to GrantedAuthority collections
 * @ param orgMap The map to process
 * @ return the processed Map */
private Map < String , Collection < GrantedAuthority > > preProcessMap ( Map < ? , ? > orgMap ) { } }

implementation: Map < String , Collection < GrantedAuthority > > result = new HashMap < String , Collection < GrantedAuthority > > ( orgMap . size ( ) ) ; for ( Map . Entry < ? , ? > entry : orgMap . entrySet ( ) ) { Assert . isInstanceOf ( String . class , entry . getKey ( ) , "attributes2grantedAuthoritiesMap contains non-String objects as keys" ) ; result . put ( ( String ) entry . getKey ( ) , getGrantedAuthorityCollection ( entry . getValue ( ) ) ) ; } return result ;


signature:
public class MapBasedAttributes2GrantedAuthoritiesMapper { /** * Convert the given value to a collection of Granted Authorities
 * @ param value The value to convert to a GrantedAuthority Collection
 * @ return Collection containing the GrantedAuthority Collection */
private Collection < GrantedAuthority > getGrantedAuthorityCollection ( Object value ) { } }

implementation: Collection < GrantedAuthority > result = new ArrayList < > ( ) ; addGrantedAuthorityCollection ( result , value ) ; return result ;


signature:
public class MapBasedAttributes2GrantedAuthoritiesMapper { /** * Convert the given value to a collection of Granted Authorities , adding the result
 * to the given result collection .
 * @ param value The value to convert to a GrantedAuthority Collection
 * @ return Collection containing the GrantedAuthority Collection */
private void addGrantedAuthorityCollection ( Collection < GrantedAuthority > result , Object value ) { } }

implementation: if ( value == null ) { return ; } if ( value instanceof Collection < ? > ) { addGrantedAuthorityCollection ( result , ( Collection < ? > ) value ) ; } else if ( value instanceof Object [ ] ) { addGrantedAuthorityCollection ( result , ( Object [ ] ) value ) ; } else if ( value instanceof String ) { addGrantedAuthorityCollection ( result , ( String ) value ) ; } else if ( value instanceof GrantedAuthority ) { result . add ( ( GrantedAuthority ) value ) ; } else { throw new IllegalArgumentException ( "Invalid object type: " + value . getClass ( ) . getName ( ) ) ; }


signature:
public class J2eePreAuthenticatedProcessingFilter { /** * Return the J2EE user name . */
protected Object getPreAuthenticatedPrincipal ( HttpServletRequest httpRequest ) { } }

implementation: Object principal = httpRequest . getUserPrincipal ( ) == null ? null : httpRequest . getUserPrincipal ( ) . getName ( ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "PreAuthenticated J2EE principal: " + principal ) ; } return principal ;


signature:
public class AbstractConfiguredSecurityBuilder { /** * Similar to { @ link # build ( ) } and { @ link # getObject ( ) } but checks the state to
 * determine if { @ link # build ( ) } needs to be called first .
 * @ return the result of { @ link # build ( ) } or { @ link # getObject ( ) } . If an error occurs
 * while building , returns null . */
public O getOrBuild ( ) { } }

implementation: if ( isUnbuilt ( ) ) { try { return build ( ) ; } catch ( Exception e ) { logger . debug ( "Failed to perform build. Returning null" , e ) ; return null ; } } else { return getObject ( ) ; }


signature:
public class AbstractConfiguredSecurityBuilder { /** * Applies a { @ link SecurityConfigurerAdapter } to this { @ link SecurityBuilder } and
 * invokes { @ link SecurityConfigurerAdapter # setBuilder ( SecurityBuilder ) } .
 * @ param configurer
 * @ return the { @ link SecurityConfigurerAdapter } for further customizations
 * @ throws Exception */
@ SuppressWarnings ( "unchecked" ) public < C extends SecurityConfigurerAdapter < O , B > > C apply ( C configurer ) throws Exception { } }

implementation: configurer . addObjectPostProcessor ( objectPostProcessor ) ; configurer . setBuilder ( ( B ) this ) ; add ( configurer ) ; return configurer ;


signature:
public class AbstractConfiguredSecurityBuilder { /** * Applies a { @ link SecurityConfigurer } to this { @ link SecurityBuilder } overriding any
 * { @ link SecurityConfigurer } of the exact same class . Note that object hierarchies
 * are not considered .
 * @ param configurer
 * @ return the { @ link SecurityConfigurerAdapter } for further customizations
 * @ throws Exception */
public < C extends SecurityConfigurer < O , B > > C apply ( C configurer ) throws Exception { } }

implementation: add ( configurer ) ; return configurer ;


signature:
public class AbstractConfiguredSecurityBuilder { /** * Sets an object that is shared by multiple { @ link SecurityConfigurer } .
 * @ param sharedType the Class to key the shared object by .
 * @ param object the Object to store */
@ SuppressWarnings ( "unchecked" ) public < C > void setSharedObject ( Class < C > sharedType , C object ) { } }

implementation: this . sharedObjects . put ( sharedType , object ) ;


signature:
public class AbstractConfiguredSecurityBuilder { /** * Gets a shared Object . Note that object heirarchies are not considered .
 * @ param sharedType the type of the shared Object
 * @ return the shared Object or null if it is not found */
@ SuppressWarnings ( "unchecked" ) public < C > C getSharedObject ( Class < C > sharedType ) { } }

implementation: return ( C ) this . sharedObjects . get ( sharedType ) ;


signature:
public class AbstractConfiguredSecurityBuilder { /** * Adds { @ link SecurityConfigurer } ensuring that it is allowed and invoking
 * { @ link SecurityConfigurer # init ( SecurityBuilder ) } immediately if necessary .
 * @ param configurer the { @ link SecurityConfigurer } to add
 * @ throws Exception if an error occurs */
@ SuppressWarnings ( "unchecked" ) private < C extends SecurityConfigurer < O , B > > void add ( C configurer ) throws Exception { } }

implementation: Assert . notNull ( configurer , "configurer cannot be null" ) ; Class < ? extends SecurityConfigurer < O , B > > clazz = ( Class < ? extends SecurityConfigurer < O , B > > ) configurer . getClass ( ) ; synchronized ( configurers ) { if ( buildState . isConfigured ( ) ) { throw new IllegalStateException ( "Cannot apply " + configurer + " to already built object" ) ; } List < SecurityConfigurer < O , B > > configs = allowConfigurersOfSameType ? this . configurers . get ( clazz ) : null ; if ( configs == null ) { configs = new ArrayList < SecurityConfigurer < O , B > > ( 1 ) ; } configs . add ( configurer ) ; this . configurers . put ( clazz , configs ) ; if ( buildState . isInitializing ( ) ) { this . configurersAddedInInitializing . add ( configurer ) ; } }


signature:
public class AbstractConfiguredSecurityBuilder { /** * Gets all the { @ link SecurityConfigurer } instances by its class name or an empty
 * List if not found . Note that object hierarchies are not considered .
 * @ param clazz the { @ link SecurityConfigurer } class to look for
 * @ return a list of { @ link SecurityConfigurer } s for further customization */
@ SuppressWarnings ( "unchecked" ) public < C extends SecurityConfigurer < O , B > > List < C > getConfigurers ( Class < C > clazz ) { } }

implementation: List < C > configs = ( List < C > ) this . configurers . get ( clazz ) ; if ( configs == null ) { return new ArrayList < > ( ) ; } return new ArrayList < > ( configs ) ;


signature:
public class AbstractConfiguredSecurityBuilder { /** * Removes all the { @ link SecurityConfigurer } instances by its class name or an empty
 * List if not found . Note that object hierarchies are not considered .
 * @ param clazz the { @ link SecurityConfigurer } class to look for
 * @ return a list of { @ link SecurityConfigurer } s for further customization */
@ SuppressWarnings ( "unchecked" ) public < C extends SecurityConfigurer < O , B > > List < C > removeConfigurers ( Class < C > clazz ) { } }

implementation: List < C > configs = ( List < C > ) this . configurers . remove ( clazz ) ; if ( configs == null ) { return new ArrayList < > ( ) ; } return new ArrayList < > ( configs ) ;


signature:
public class AbstractConfiguredSecurityBuilder { /** * Removes and returns the { @ link SecurityConfigurer } by its class name or
 * < code > null < / code > if not found . Note that object hierarchies are not considered .
 * @ param clazz
 * @ return */
@ SuppressWarnings ( "unchecked" ) public < C extends SecurityConfigurer < O , B > > C removeConfigurer ( Class < C > clazz ) { } }

implementation: List < SecurityConfigurer < O , B > > configs = this . configurers . remove ( clazz ) ; if ( configs == null ) { return null ; } if ( configs . size ( ) != 1 ) { throw new IllegalStateException ( "Only one configurer expected for type " + clazz + ", but got " + configs ) ; } return ( C ) configs . get ( 0 ) ;


signature:
public class AbstractConfiguredSecurityBuilder { /** * Specifies the { @ link ObjectPostProcessor } to use .
 * @ param objectPostProcessor the { @ link ObjectPostProcessor } to use . Cannot be null
 * @ return the { @ link SecurityBuilder } for further customizations */
@ SuppressWarnings ( "unchecked" ) public O objectPostProcessor ( ObjectPostProcessor < Object > objectPostProcessor ) { } }

implementation: Assert . notNull ( objectPostProcessor , "objectPostProcessor cannot be null" ) ; this . objectPostProcessor = objectPostProcessor ; return ( O ) this ;


signature:
public class AbstractConfiguredSecurityBuilder { /** * Executes the build using the { @ link SecurityConfigurer } ' s that have been applied
 * using the following steps :
 * < ul >
 * < li > Invokes { @ link # beforeInit ( ) } for any subclass to hook into < / li >
 * < li > Invokes { @ link SecurityConfigurer # init ( SecurityBuilder ) } for any
 * { @ link SecurityConfigurer } that was applied to this builder . < / li >
 * < li > Invokes { @ link # beforeConfigure ( ) } for any subclass to hook into < / li >
 * < li > Invokes { @ link # performBuild ( ) } which actually builds the Object < / li >
 * < / ul > */
@ Override protected final O doBuild ( ) throws Exception { } }

implementation: synchronized ( configurers ) { buildState = BuildState . INITIALIZING ; beforeInit ( ) ; init ( ) ; buildState = BuildState . CONFIGURING ; beforeConfigure ( ) ; configure ( ) ; buildState = BuildState . BUILDING ; O result = performBuild ( ) ; buildState = BuildState . BUILT ; return result ; }


signature: public class AbstractAclVoter { protected Object getDomainObjectInstance ( MethodInvocation invocation ) { } }

implementation: Object [ ] args ; Class < ? > [ ] params ; params = invocation . getMethod ( ) . getParameterTypes ( ) ; args = invocation . getArguments ( ) ; for ( int i = 0 ; i < params . length ; i ++ ) { if ( processDomainObjectClass . isAssignableFrom ( params [ i ] ) ) { return args [ i ] ; } } throw new AuthorizationServiceException ( "MethodInvocation: " + invocation + " did not provide any argument of type: " + processDomainObjectClass ) ;


signature: public class LoginUrlAuthenticationEntryPoint { public void afterPropertiesSet ( ) throws Exception { } }

implementation: Assert . isTrue ( StringUtils . hasText ( loginFormUrl ) && UrlUtils . isValidRedirectUrl ( loginFormUrl ) , "loginFormUrl must be specified and must be a valid redirect URL" ) ; if ( useForward && UrlUtils . isAbsoluteUrl ( loginFormUrl ) ) { throw new IllegalArgumentException ( "useForward must be false if using an absolute loginFormURL" ) ; } Assert . notNull ( portMapper , "portMapper must be specified" ) ; Assert . notNull ( portResolver , "portResolver must be specified" ) ;


signature:
public class LoginUrlAuthenticationEntryPoint { /** * Performs the redirect ( or forward ) to the login form URL . */
public void commence ( HttpServletRequest request , HttpServletResponse response , AuthenticationException authException ) throws IOException , ServletException { } }

implementation:
String redirectUrl = null ; if ( useForward ) { if ( forceHttps && "http" . equals ( request . getScheme ( ) ) ) { // First redirect the current request to HTTPS .
// When that request is received , the forward to the login page will be
// used .
redirectUrl = buildHttpsRedirectUrlForRequest ( request ) ; } if ( redirectUrl == null ) { String loginForm = determineUrlToUseForThisRequest ( request , response , authException ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Server side forward to: " + loginForm ) ; } RequestDispatcher dispatcher = request . getRequestDispatcher ( loginForm ) ; dispatcher . forward ( request , response ) ; return ; } } else { // redirect to login page . Use https if forceHttps true
redirectUrl = buildRedirectUrlToLoginPage ( request , response , authException ) ; } redirectStrategy . sendRedirect ( request , response , redirectUrl ) ;


signature:
public class LoginUrlAuthenticationEntryPoint { /** * Builds a URL to redirect the supplied request to HTTPS . Used to redirect the
 * current request to HTTPS , before doing a forward to the login page . */
protected String buildHttpsRedirectUrlForRequest ( HttpServletRequest request ) throws IOException , ServletException { } }

implementation:
int serverPort = portResolver . getServerPort ( request ) ; Integer httpsPort = portMapper . lookupHttpsPort ( Integer . valueOf ( serverPort ) ) ; if ( httpsPort != null ) { RedirectUrlBuilder urlBuilder = new RedirectUrlBuilder ( ) ; urlBuilder . setScheme ( "https" ) ; urlBuilder . setServerName ( request . getServerName ( ) ) ; urlBuilder . setPort ( httpsPort . intValue ( ) ) ; urlBuilder . setContextPath ( request . getContextPath ( ) ) ; urlBuilder . setServletPath ( request . getServletPath ( ) ) ; urlBuilder . setPathInfo ( request . getPathInfo ( ) ) ; urlBuilder . setQuery ( request . getQueryString ( ) ) ; return urlBuilder . getUrl ( ) ; } // Fall through to server - side forward with warning message
logger . warn ( "Unable to redirect to HTTPS as no port mapping found for HTTP port " + serverPort ) ; return null ;


signature:
public class AspectJMethodSecurityInterceptor { /** * Method that is suitable for user with traditional AspectJ - code aspects .
 * @ param jp The AspectJ joint point being invoked which requires a security decision
 * @ param advisorProceed the advice - defined anonymous class that implements
 * { @ code AspectJCallback } containing a simple { @ code return proceed ( ) ; } statement
 * @ return The returned value from the method invocation */
public Object invoke ( JoinPoint jp , AspectJCallback advisorProceed ) { } }

implementation: InterceptorStatusToken token = super . beforeInvocation ( new MethodInvocationAdapter ( jp ) ) ; Object result ; try { result = advisorProceed . proceedWithObject ( ) ; } finally { super . finallyInvocation ( token ) ; } return super . afterInvocation ( token , result ) ;


signature:
public class UrlAuthorizationConfigurer { /** * Creates the default { @ link AccessDecisionVoter } instances used if an
 * { @ link AccessDecisionManager } was not specified .
 * @ param http the builder to use */
@ Override @ SuppressWarnings ( "rawtypes" ) final List < AccessDecisionVoter < ? extends Object > > getDecisionVoters ( H http ) { } }

implementation: List < AccessDecisionVoter < ? extends Object > > decisionVoters = new ArrayList < AccessDecisionVoter < ? extends Object > > ( ) ; decisionVoters . add ( new RoleVoter ( ) ) ; decisionVoters . add ( new AuthenticatedVoter ( ) ) ; return decisionVoters ;


signature:
public class UrlAuthorizationConfigurer { /** * Creates a String for specifying a user requires a role .
 * @ param role the role that should be required which is prepended with ROLE _
 * automatically ( i . e . USER , ADMIN , etc ) . It should not start with ROLE _
 * @ return the { @ link ConfigAttribute } expressed as a String */
private static String hasRole ( String role ) { } }

implementation: Assert . isTrue ( ! role . startsWith ( "ROLE_" ) , ( ) -> role + " should not start with ROLE_ since ROLE_ is automatically prepended when using hasRole. Consider using hasAuthority or access instead." ) ; return "ROLE_" + role ;


signature:
public class UrlAuthorizationConfigurer { /** * Creates a String for specifying that a user requires one of many roles .
 * @ param roles the roles that the user should have at least one of ( i . e . ADMIN , USER ,
 * etc ) . Each role should not start with ROLE _ since it is automatically prepended
 * already .
 * @ return the { @ link ConfigAttribute } expressed as a String */
private static String [ ] hasAnyRole ( String ... roles ) { } }

implementation: for ( int i = 0 ; i < roles . length ; i ++ ) { roles [ i ] = "ROLE_" + roles [ i ] ; } return roles ;


signature:
public class SubjectDnX509PrincipalExtractor { /** * Sets the regular expression which will by used to extract the user name from the
 * certificate ' s Subject DN .
 * It should contain a single group ; for example the default expression
 * " CN = ( . * ? ) ( ? : , | $ ) " matches the common name field . So " CN = Jimi Hendrix , OU = . . . " will
 * give a user name of " Jimi Hendrix " .
 * The matches are case insensitive . So " emailAddress = ( . ? ) , " will match
 * " EMAILADDRESS = jimi @ hendrix . org , CN = . . . " giving a user name " jimi @ hendrix . org "
 * @ param subjectDnRegex the regular expression to find in the subject */
public void setSubjectDnRegex ( String subjectDnRegex ) { } }

implementation: Assert . hasText ( subjectDnRegex , "Regular expression may not be null or empty" ) ; subjectDnPattern = Pattern . compile ( subjectDnRegex , Pattern . CASE_INSENSITIVE ) ;


signature:
public class AndServerWebExchangeMatcher { /** * / * ( non - Javadoc )
 * @ see org . springframework . security . web . server . util . matcher . ServerWebExchangeMatcher # matches ( org . springframework . web . server . ServerWebExchange ) */
@ Override public Mono < MatchResult > matches ( ServerWebExchange exchange ) { } }

implementation: return Mono . defer ( ( ) -> { Map < String , Object > variables = new HashMap < > ( ) ; return Flux . fromIterable ( matchers ) . flatMap ( matcher -> matcher . matches ( exchange ) ) . doOnNext ( matchResult -> variables . putAll ( matchResult . getVariables ( ) ) ) . all ( MatchResult :: isMatch ) . flatMap ( allMatch -> allMatch ? MatchResult . match ( variables ) : MatchResult . notMatch ( ) ) ; } ) ;


signature:
public class PersistentTokenBasedRememberMeServices { /** * Locates the presented cookie data in the token repository , using the series id . If
 * the data compares successfully with that in the persistent store , a new token is
 * generated and stored with the same series . The corresponding cookie value is set on
 * the response .
 * @ param cookieTokens the series and token values
 * @ throws RememberMeAuthenticationException if there is no stored token corresponding
 * to the submitted cookie , or if the token in the persistent store has expired .
 * @ throws InvalidCookieException if the cookie doesn ' t have two tokens as expected .
 * @ throws CookieTheftException if a presented series value is found , but the stored
 * token is different from the one presented . */
protected UserDetails processAutoLoginCookie ( String [ ] cookieTokens , HttpServletRequest request , HttpServletResponse response ) { } }

implementation:
if ( cookieTokens . length != 2 ) { throw new InvalidCookieException ( "Cookie token did not contain " + 2 + " tokens, but contained '" + Arrays . asList ( cookieTokens ) + "'" ) ; } final String presentedSeries = cookieTokens [ 0 ] ; final String presentedToken = cookieTokens [ 1 ] ; PersistentRememberMeToken token = tokenRepository . getTokenForSeries ( presentedSeries ) ; if ( token == null ) { // No series match , so we can ' t authenticate using this cookie
throw new RememberMeAuthenticationException ( "No persistent token found for series id: " + presentedSeries ) ; } // We have a match for this user / series combination
if ( ! presentedToken . equals ( token . getTokenValue ( ) ) ) { // Token doesn ' t match series value . Delete all logins for this user and throw
// an exception to warn them .
tokenRepository . removeUserTokens ( token . getUsername ( ) ) ; throw new CookieTheftException ( messages . getMessage ( "PersistentTokenBasedRememberMeServices.cookieStolen" , "Invalid remember-me token (Series/token) mismatch. Implies previous cookie theft attack." ) ) ; } if ( token . getDate ( ) . getTime ( ) + getTokenValiditySeconds ( ) * 1000L < System . currentTimeMillis ( ) ) { throw new RememberMeAuthenticationException ( "Remember-me login has expired" ) ; } // Token also matches , so login is valid . Update the token value , keeping the
// * same * series number .
if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Refreshing persistent login token for user '" + token . getUsername ( ) + "', series '" + token . getSeries ( ) + "'" ) ; } PersistentRememberMeToken newToken = new PersistentRememberMeToken ( token . getUsername ( ) , token . getSeries ( ) , generateTokenData ( ) , new Date ( ) ) ; try { tokenRepository . updateToken ( newToken . getSeries ( ) , newToken . getTokenValue ( ) , newToken . getDate ( ) ) ; addCookie ( newToken , request , response ) ; } catch ( Exception e ) { logger . error ( "Failed to update token: " , e ) ; throw new RememberMeAuthenticationException ( "Autologin failed due to data access problem" ) ; } return getUserDetailsService ( ) . loadUserByUsername ( token . getUsername ( ) ) ;


signature:
public class PersistentTokenBasedRememberMeServices { /** * Creates a new persistent login token with a new series number , stores the data in
 * the persistent token repository and adds the corresponding cookie to the response . */
protected void onLoginSuccess ( HttpServletRequest request , HttpServletResponse response , Authentication successfulAuthentication ) { } }

implementation: String username = successfulAuthentication . getName ( ) ; logger . debug ( "Creating new persistent login for user " + username ) ; PersistentRememberMeToken persistentToken = new PersistentRememberMeToken ( username , generateSeriesData ( ) , generateTokenData ( ) , new Date ( ) ) ; try { tokenRepository . createNewToken ( persistentToken ) ; addCookie ( persistentToken , request , response ) ; } catch ( Exception e ) { logger . error ( "Failed to save persistent token " , e ) ; }


signature: public class SwitchUserFilter { @ Override public void afterPropertiesSet ( ) { } }

implementation: Assert . notNull ( this . userDetailsService , "userDetailsService must be specified" ) ; Assert . isTrue ( this . successHandler != null || this . targetUrl != null , "You must set either a successHandler or the targetUrl" ) ; if ( this . targetUrl != null ) { Assert . isNull ( this . successHandler , "You cannot set both successHandler and targetUrl" ) ; this . successHandler = new SimpleUrlAuthenticationSuccessHandler ( this . targetUrl ) ; } if ( this . failureHandler == null ) { this . failureHandler = this . switchFailureUrl == null ? new SimpleUrlAuthenticationFailureHandler ( ) : new SimpleUrlAuthenticationFailureHandler ( this . switchFailureUrl ) ; } else { Assert . isNull ( this . switchFailureUrl , "You cannot set both a switchFailureUrl and a failureHandler" ) ; }


signature:
public class SwitchUserFilter { /** * Attempt to switch to another user . If the user does not exist or is not active ,
 * return null .
 * @ return The new < code > Authentication < / code > request if successfully switched to
 * another user , < code > null < / code > otherwise .
 * @ throws UsernameNotFoundException If the target user is not found .
 * @ throws LockedException if the account is locked .
 * @ throws DisabledException If the target user is disabled .
 * @ throws AccountExpiredException If the target user account is expired .
 * @ throws CredentialsExpiredException If the target user credentials are expired . */
protected Authentication attemptSwitchUser ( HttpServletRequest request ) throws AuthenticationException { } }

implementation:
UsernamePasswordAuthenticationToken targetUserRequest ; String username = request . getParameter ( this . usernameParameter ) ; if ( username == null ) { username = "" ; } if ( this . logger . isDebugEnabled ( ) ) { this . logger . debug ( "Attempt to switch to user [" + username + "]" ) ; } UserDetails targetUser = this . userDetailsService . loadUserByUsername ( username ) ; this . userDetailsChecker . check ( targetUser ) ; // OK , create the switch user token
targetUserRequest = createSwitchUserToken ( request , targetUser ) ; if ( this . logger . isDebugEnabled ( ) ) { this . logger . debug ( "Switch User Token [" + targetUserRequest + "]" ) ; } // publish event
if ( this . eventPublisher != null ) { this . eventPublisher . publishEvent ( new AuthenticationSwitchUserEvent ( SecurityContextHolder . getContext ( ) . getAuthentication ( ) , targetUser ) ) ; } return targetUserRequest ;


signature:
public class SwitchUserFilter { /** * Attempt to exit from an already switched user .
 * @ param request The http servlet request
 * @ return The original < code > Authentication < / code > object or < code > null < / code >
 * otherwise .
 * @ throws AuthenticationCredentialsNotFoundException If no
 * < code > Authentication < / code > associated with this request . */
protected Authentication attemptExitUser ( HttpServletRequest request ) throws AuthenticationCredentialsNotFoundException { } }

implementation:
// need to check to see if the current user has a SwitchUserGrantedAuthority
Authentication current = SecurityContextHolder . getContext ( ) . getAuthentication ( ) ; if ( null == current ) { throw new AuthenticationCredentialsNotFoundException ( this . messages . getMessage ( "SwitchUserFilter.noCurrentUser" , "No current user associated with this request" ) ) ; } // check to see if the current user did actual switch to another user
// if so , get the original source user so we can switch back
Authentication original = getSourceAuthentication ( current ) ; if ( original == null ) { this . logger . debug ( "Could not find original user Authentication object!" ) ; throw new AuthenticationCredentialsNotFoundException ( this . messages . getMessage ( "SwitchUserFilter.noOriginalAuthentication" , "Could not find original Authentication object" ) ) ; } // get the source user details
UserDetails originalUser = null ; Object obj = original . getPrincipal ( ) ; if ( ( obj != null ) && obj instanceof UserDetails ) { originalUser = ( UserDetails ) obj ; } // publish event
if ( this . eventPublisher != null ) { this . eventPublisher . publishEvent ( new AuthenticationSwitchUserEvent ( current , originalUser ) ) ; } return original ;


signature:
public class SwitchUserFilter { /** * Create a switch user token that contains an additional < tt > GrantedAuthority < / tt >
 * that contains the original < code > Authentication < / code > object .
 * @ param request The http servlet request .
 * @ param targetUser The target user
 * @ return The authentication token
 * @ see SwitchUserGrantedAuthority */
private UsernamePasswordAuthenticationToken createSwitchUserToken ( HttpServletRequest request , UserDetails targetUser ) { } }

implementation:
UsernamePasswordAuthenticationToken targetUserRequest ; // grant an additional authority that contains the original Authentication object
// which will be used to ' exit ' from the current switched user .
Authentication currentAuth ; try { // SEC - 1763 . Check first if we are already switched .
currentAuth = attemptExitUser ( request ) ; } catch ( AuthenticationCredentialsNotFoundException e ) { currentAuth = SecurityContextHolder . getContext ( ) . getAuthentication ( ) ; } GrantedAuthority switchAuthority = new SwitchUserGrantedAuthority ( this . switchAuthorityRole , currentAuth ) ; // get the original authorities
Collection < ? extends GrantedAuthority > orig = targetUser . getAuthorities ( ) ; // Allow subclasses to change the authorities to be granted
if ( this . switchUserAuthorityChanger != null ) { orig = this . switchUserAuthorityChanger . modifyGrantedAuthorities ( targetUser , currentAuth , orig ) ; } // add the new switch user authority
List < GrantedAuthority > newAuths = new ArrayList < > ( orig ) ; newAuths . add ( switchAuthority ) ; // create the new authentication token
targetUserRequest = new UsernamePasswordAuthenticationToken ( targetUser , targetUser . getPassword ( ) , newAuths ) ; // set details
targetUserRequest . setDetails ( this . authenticationDetailsSource . buildDetails ( request ) ) ; return targetUserRequest ;


signature:
public class SwitchUserFilter { /** * Find the original < code > Authentication < / code > object from the current user ' s
 * granted authorities . A successfully switched user should have a
 * < code > SwitchUserGrantedAuthority < / code > that contains the original source user
 * < code > Authentication < / code > object .
 * @ param current The current < code > Authentication < / code > object
 * @ return The source user < code > Authentication < / code > object or < code > null < / code >
 * otherwise . */
private Authentication getSourceAuthentication ( Authentication current ) { } }

implementation:
Authentication original = null ; // iterate over granted authorities and find the ' switch user ' authority
Collection < ? extends GrantedAuthority > authorities = current . getAuthorities ( ) ; for ( GrantedAuthority auth : authorities ) { // check for switch user type of authority
if ( auth instanceof SwitchUserGrantedAuthority ) { original = ( ( SwitchUserGrantedAuthority ) auth ) . getSource ( ) ; this . logger . debug ( "Found original switch user granted authority [" + original + "]" ) ; } } return original ;


signature:
public class SwitchUserFilter { /** * Set the URL to respond to exit user processing .
 * @ param exitUserUrl The exit user URL . */
public void setExitUserUrl ( String exitUserUrl ) { } }

implementation: Assert . isTrue ( UrlUtils . isValidRedirectUrl ( exitUserUrl ) , "exitUserUrl cannot be empty and must be a valid redirect URL" ) ; this . exitUserMatcher = createMatcher ( exitUserUrl ) ;


signature:
public class SwitchUserFilter { /** * Set the URL to respond to switch user processing . This is a shortcut for
 * { @ link # setSwitchUserMatcher ( RequestMatcher ) }
 * @ param switchUserUrl The switch user URL . */
public void setSwitchUserUrl ( String switchUserUrl ) { } }

implementation: Assert . isTrue ( UrlUtils . isValidRedirectUrl ( switchUserUrl ) , "switchUserUrl cannot be empty and must be a valid redirect URL" ) ; this . switchUserMatcher = createMatcher ( switchUserUrl ) ;


signature:
public class SwitchUserFilter { /** * Sets the URL to which a user should be redirected if the switch fails . For example ,
 * this might happen because the account they are attempting to switch to is invalid
 * ( the user doesn ' t exist , account is locked etc ) .
 * If not set , an error message will be written to the response .
 * Use { @ link # setFailureHandler ( AuthenticationFailureHandler ) failureHandler } instead
 * if you need more customized behaviour .
 * @ param switchFailureUrl the url to redirect to . */
public void setSwitchFailureUrl ( String switchFailureUrl ) { } }

implementation: Assert . isTrue ( UrlUtils . isValidRedirectUrl ( switchFailureUrl ) , "switchFailureUrl must be a valid redirect URL" ) ; this . switchFailureUrl = switchFailureUrl ;


signature:
public class IndexController { /** * The public index page , used for unauthenticated users . */
@ RequestMapping ( value = "/hello.htm" , method = RequestMethod . GET ) public ModelAndView displayPublicIndex ( ) { } }

implementation: Contact rnd = contactManager . getRandomContact ( ) ; return new ModelAndView ( "hello" , "contact" , rnd ) ;


signature:
public class IndexController { /** * The index page for an authenticated user .
 * This controller displays a list of all the contacts for which the current user has
 * read or admin permissions . It makes a call to { @ link ContactManager # getAll ( ) } which
 * automatically filters the returned list using Spring Security ' s ACL mechanism ( see
 * the expression annotations on this interface for the details ) .
 * In addition to rendering the list of contacts , the view will also include a " Del "
 * or " Admin " link beside the contact , depending on whether the user has the
 * corresponding permissions ( admin permission is assumed to imply delete here ) . This
 * information is stored in the model using the injected { @ link PermissionEvaluator }
 * instance . The implementation should be an instance of
 * { @ link AclPermissionEvaluator } or one which is compatible with Spring Security ' s
 * ACL module . */
@ RequestMapping ( value = "/secure/index.htm" , method = RequestMethod . GET ) public ModelAndView displayUserContacts ( ) { } }

implementation: List < Contact > myContactsList = contactManager . getAll ( ) ; Map < Contact , Boolean > hasDelete = new HashMap < > ( myContactsList . size ( ) ) ; Map < Contact , Boolean > hasAdmin = new HashMap < > ( myContactsList . size ( ) ) ; Authentication user = SecurityContextHolder . getContext ( ) . getAuthentication ( ) ; for ( Contact contact : myContactsList ) { hasDelete . put ( contact , Boolean . valueOf ( permissionEvaluator . hasPermission ( user , contact , HAS_DELETE ) ) ) ; hasAdmin . put ( contact , Boolean . valueOf ( permissionEvaluator . hasPermission ( user , contact , HAS_ADMIN ) ) ) ; } Map < String , Object > model = new HashMap < > ( ) ; model . put ( "contacts" , myContactsList ) ; model . put ( "hasDeletePermission" , hasDelete ) ; model . put ( "hasAdminPermission" , hasAdmin ) ; return new ModelAndView ( "index" , "model" , model ) ;


signature:
public class RequestWrapper { /** * Removes path parameters from each path segment in the supplied path and truncates
 * sequences of multiple ' / ' characters to a single ' / ' .
 * @ param path either the { @ code servletPath } and { @ code pathInfo } from the original
 * request
 * @ return the supplied value , with path parameters removed and sequences of multiple
 * ' / ' characters truncated , or null if the supplied path was null . */
private String strip ( String path ) { } }

implementation:
if ( path == null ) { return null ; } int scIndex = path . indexOf ( ';' ) ; if ( scIndex < 0 ) { int doubleSlashIndex = path . indexOf ( "//" ) ; if ( doubleSlashIndex < 0 ) { // Most likely case , no parameters in any segment and no ' / / ' , so no
// stripping required
return path ; } } StringTokenizer st = new StringTokenizer ( path , "/" ) ; StringBuilder stripped = new StringBuilder ( path . length ( ) ) ; if ( path . charAt ( 0 ) == '/' ) { stripped . append ( '/' ) ; } while ( st . hasMoreTokens ( ) ) { String segment = st . nextToken ( ) ; scIndex = segment . indexOf ( ';' ) ; if ( scIndex >= 0 ) { segment = segment . substring ( 0 , scIndex ) ; } stripped . append ( segment ) . append ( '/' ) ; } // Remove the trailing slash if the original path didn ' t have one
if ( path . charAt ( path . length ( ) - 1 ) != '/' ) { stripped . deleteCharAt ( stripped . length ( ) - 1 ) ; } return stripped . toString ( ) ;


signature:
public class WebSecurityConfiguration { /** * Creates the Spring Security Filter Chain
 * @ return the { @ link Filter } that represents the security filter chain
 * @ throws Exception */
@ Bean ( name = AbstractSecurityWebApplicationInitializer . DEFAULT_FILTER_NAME ) public Filter springSecurityFilterChain ( ) throws Exception { } }

implementation: boolean hasConfigurers = webSecurityConfigurers != null && ! webSecurityConfigurers . isEmpty ( ) ; if ( ! hasConfigurers ) { WebSecurityConfigurerAdapter adapter = objectObjectPostProcessor . postProcess ( new WebSecurityConfigurerAdapter ( ) { } ) ; webSecurity . apply ( adapter ) ; } return webSecurity . build ( ) ;


signature:
public class WebSecurityConfiguration { /** * Sets the { @ code < SecurityConfigurer < FilterChainProxy , WebSecurityBuilder > }
 * instances used to create the web configuration .
 * @ param objectPostProcessor the { @ link ObjectPostProcessor } used to create a
 * { @ link WebSecurity } instance
 * @ param webSecurityConfigurers the
 * { @ code < SecurityConfigurer < FilterChainProxy , WebSecurityBuilder > } instances used to
 * create the web configuration
 * @ throws Exception */
@ Autowired ( required = false ) public void setFilterChainProxySecurityConfigurer ( ObjectPostProcessor < Object > objectPostProcessor , @ Value ( "#{@autowiredWebSecurityConfigurersIgnoreParents.getWebSecurityConfigurers()}" ) List < SecurityConfigurer < Filter , WebSecurity > > webSecurityConfigurers ) throws Exception { } }

implementation: webSecurity = objectPostProcessor . postProcess ( new WebSecurity ( objectPostProcessor ) ) ; if ( debugEnabled != null ) { webSecurity . debug ( debugEnabled ) ; } Collections . sort ( webSecurityConfigurers , AnnotationAwareOrderComparator . INSTANCE ) ; Integer previousOrder = null ; Object previousConfig = null ; for ( SecurityConfigurer < Filter , WebSecurity > config : webSecurityConfigurers ) { Integer order = AnnotationAwareOrderComparator . lookupOrder ( config ) ; if ( previousOrder != null && previousOrder . equals ( order ) ) { throw new IllegalStateException ( "@Order on WebSecurityConfigurers must be unique. Order of " + order + " was already used on " + previousConfig + ", so it cannot be used on " + config + " too." ) ; } previousOrder = order ; previousConfig = config ; } for ( SecurityConfigurer < Filter , WebSecurity > webSecurityConfigurer : webSecurityConfigurers ) { webSecurity . apply ( webSecurityConfigurer ) ; } this . webSecurityConfigurers = webSecurityConfigurers ;


signature:
public class WebSecurityConfiguration { /** * ( non - Javadoc )
 * @ see org . springframework . context . annotation . ImportAware # setImportMetadata ( org .
 * springframework . core . type . AnnotationMetadata ) */
public void setImportMetadata ( AnnotationMetadata importMetadata ) { } }

implementation: Map < String , Object > enableWebSecurityAttrMap = importMetadata . getAnnotationAttributes ( EnableWebSecurity . class . getName ( ) ) ; AnnotationAttributes enableWebSecurityAttrs = AnnotationAttributes . fromMap ( enableWebSecurityAttrMap ) ; debugEnabled = enableWebSecurityAttrs . getBoolean ( "debug" ) ; if ( webSecurity != null ) { webSecurity . debug ( debugEnabled ) ; }


signature:
public class ExpressionBasedMessageSecurityMetadataSourceFactory { /** * Create a { @ link MessageSecurityMetadataSource } that uses { @ link MessageMatcher }
 * mapped to Spring Expressions . Each entry is considered in order and only the first
 * match is used .
 * For example :
 * < pre >
 * LinkedHashMap & lt ; MessageMatcher & lt ; ? & gt ; , String & gt ; matcherToExpression = new LinkedHashMap & lt ; MessageMatcher & lt ; Object & gt ; , String & gt ; ( ) ;
 * matcherToExpression . put ( new SimDestinationMessageMatcher ( " / public / * * " ) , " permitAll " ) ;
 * matcherToExpression . put ( new SimDestinationMessageMatcher ( " / admin / * * " ) , " hasRole ( ' ROLE _ ADMIN ' ) " ) ;
 * matcherToExpression . put ( new SimDestinationMessageMatcher ( " / * * " ) , " authenticated " ) ;
 * MessageSecurityMetadataSource metadataSource = createExpressionMessageMetadataSource ( matcherToExpression ) ;
 * < / pre >
 * If our destination is " / public / hello " , it would match on " / public / * * " and on " / * * " .
 * However , only " / public / * * " would be used since it is the first entry . That means
 * that a destination of " / public / hello " will be mapped to " permitAll " .
 * For a complete listing of expressions see { @ link MessageSecurityExpressionRoot }
 * @ param matcherToExpression an ordered mapping of { @ link MessageMatcher } to Strings
 * that are turned into an Expression using
 * { @ link DefaultMessageSecurityExpressionHandler # getExpressionParser ( ) }
 * @ param handler the { @ link SecurityExpressionHandler } to use
 * @ return the { @ link MessageSecurityMetadataSource } to use . Cannot be null . */
public static MessageSecurityMetadataSource createExpressionMessageMetadataSource ( LinkedHashMap < MessageMatcher < ? > , String > matcherToExpression , SecurityExpressionHandler < Message < Object > > handler ) { } }

implementation: LinkedHashMap < MessageMatcher < ? > , Collection < ConfigAttribute > > matcherToAttrs = new LinkedHashMap < MessageMatcher < ? > , Collection < ConfigAttribute > > ( ) ; for ( Map . Entry < MessageMatcher < ? > , String > entry : matcherToExpression . entrySet ( ) ) { MessageMatcher < ? > matcher = entry . getKey ( ) ; String rawExpression = entry . getValue ( ) ; Expression expression = handler . getExpressionParser ( ) . parseExpression ( rawExpression ) ; ConfigAttribute attribute = new MessageExpressionConfigAttribute ( expression ) ; matcherToAttrs . put ( matcher , Arrays . asList ( attribute ) ) ; } return new DefaultMessageSecurityMetadataSource ( matcherToAttrs ) ;


signature:
public class NimbusJwtDecoder { /** * Decode and validate the JWT from its compact claims representation format
 * @ param token the JWT value
 * @ return a validated { @ link Jwt }
 * @ throws JwtException */
@ Override public Jwt decode ( String token ) throws JwtException { } }

implementation: JWT jwt = parse ( token ) ; if ( jwt instanceof SignedJWT ) { Jwt createdJwt = createJwt ( token , jwt ) ; return validateJwt ( createdJwt ) ; } throw new JwtException ( "Unsupported algorithm of " + jwt . getHeader ( ) . getAlgorithm ( ) ) ;


signature:
public class DelegatingAuthenticationFailureHandler { /** * { @ inheritDoc } */
@ Override public void onAuthenticationFailure ( HttpServletRequest request , HttpServletResponse response , AuthenticationException exception ) throws IOException , ServletException { } }

implementation: for ( Map . Entry < Class < ? extends AuthenticationException > , AuthenticationFailureHandler > entry : handlers . entrySet ( ) ) { Class < ? extends AuthenticationException > handlerMappedExceptionClass = entry . getKey ( ) ; if ( handlerMappedExceptionClass . isAssignableFrom ( exception . getClass ( ) ) ) { AuthenticationFailureHandler handler = entry . getValue ( ) ; handler . onAuthenticationFailure ( request , response , exception ) ; return ; } } defaultHandler . onAuthenticationFailure ( request , response , exception ) ;


signature:
public class AbstractAccessDecisionManager { /** * Iterates through all < code > AccessDecisionVoter < / code > s and ensures each can support
 * the presented class .
 * If one or more voters cannot support the presented class , < code > false < / code > is
 * returned .
 * @ param clazz the type of secured object being presented
 * @ return true if this type is supported */
public boolean supports ( Class < ? > clazz ) { } }

implementation: for ( AccessDecisionVoter voter : this . decisionVoters ) { if ( ! voter . supports ( clazz ) ) { return false ; } } return true ;


signature:
public class NimbusReactiveOAuth2TokenIntrospectionClient { /** * { @ inheritDoc } */
@ Override public Mono < Map < String , Object > > introspect ( String token ) { } }

implementation: return Mono . just ( token ) . flatMap ( this :: makeRequest ) . flatMap ( this :: adaptToNimbusResponse ) . map ( this :: parseNimbusResponse ) . map ( this :: castToNimbusSuccess ) . doOnNext ( response -> validate ( token , response ) ) . map ( this :: convertClaimsSet ) . onErrorMap ( e -> ! ( e instanceof OAuth2IntrospectionException ) , this :: onError ) ;


signature:
public class AbstractAuthorizeTag { /** * Make an authorization decision by considering all & lt ; authorize & gt ; tag attributes .
 * The following are valid combinations of attributes :
 * < ul >
 * < li > access < / li >
 * < li > url , method < / li >
 * < / ul >
 * The above combinations are mutually exclusive and evaluated in the given order .
 * @ return the result of the authorization decision
 * @ throws IOException */
public boolean authorize ( ) throws IOException { } }

implementation: boolean isAuthorized ; if ( StringUtils . hasText ( getAccess ( ) ) ) { isAuthorized = authorizeUsingAccessExpression ( ) ; } else if ( StringUtils . hasText ( getUrl ( ) ) ) { isAuthorized = authorizeUsingUrlCheck ( ) ; } else { isAuthorized = false ; } return isAuthorized ;


signature:
public class AbstractAuthorizeTag { /** * Make an authorization decision based on a Spring EL expression . See the
 * " Expression - Based Access Control " chapter in Spring Security for details on what
 * expressions can be used .
 * @ return the result of the authorization decision
 * @ throws IOException */
public boolean authorizeUsingAccessExpression ( ) throws IOException { } }

implementation: if ( SecurityContextHolder . getContext ( ) . getAuthentication ( ) == null ) { return false ; } SecurityExpressionHandler < FilterInvocation > handler = getExpressionHandler ( ) ; Expression accessExpression ; try { accessExpression = handler . getExpressionParser ( ) . parseExpression ( getAccess ( ) ) ; } catch ( ParseException e ) { IOException ioException = new IOException ( ) ; ioException . initCause ( e ) ; throw ioException ; } return ExpressionUtils . evaluateAsBoolean ( accessExpression , createExpressionEvaluationContext ( handler ) ) ;


signature:
public class AbstractAuthorizeTag { /** * Allows the { @ code EvaluationContext } to be customized for variable lookup etc . */
protected EvaluationContext createExpressionEvaluationContext ( SecurityExpressionHandler < FilterInvocation > handler ) { } }

implementation: FilterInvocation f = new FilterInvocation ( getRequest ( ) , getResponse ( ) , new FilterChain ( ) { public void doFilter ( ServletRequest request , ServletResponse response ) throws IOException , ServletException { throw new UnsupportedOperationException ( ) ; } } ) ; return handler . createEvaluationContext ( SecurityContextHolder . getContext ( ) . getAuthentication ( ) , f ) ;


signature:
public class AbstractAuthorizeTag { /** * Make an authorization decision based on the URL and HTTP method attributes . True is
 * returned if the user is allowed to access the given URL as defined .
 * @ return the result of the authorization decision
 * @ throws IOException */
public boolean authorizeUsingUrlCheck ( ) throws IOException { } }

implementation: String contextPath = ( ( HttpServletRequest ) getRequest ( ) ) . getContextPath ( ) ; Authentication currentUser = SecurityContextHolder . getContext ( ) . getAuthentication ( ) ; return getPrivilegeEvaluator ( ) . isAllowed ( contextPath , getUrl ( ) , getMethod ( ) , currentUser ) ;


signature:
public class AbstractAuthorizeTag { /** * / * - - - - - Private helper methods - - - - - */
@ SuppressWarnings ( { } }

implementation: "unchecked" , "rawtypes" } ) private SecurityExpressionHandler < FilterInvocation > getExpressionHandler ( ) throws IOException { ApplicationContext appContext = SecurityWebApplicationContextUtils . findRequiredWebApplicationContext ( getServletContext ( ) ) ; Map < String , SecurityExpressionHandler > handlers = appContext . getBeansOfType ( SecurityExpressionHandler . class ) ; for ( SecurityExpressionHandler h : handlers . values ( ) ) { if ( FilterInvocation . class . equals ( GenericTypeResolver . resolveTypeArgument ( h . getClass ( ) , SecurityExpressionHandler . class ) ) ) { return h ; } } throw new IOException ( "No visible WebSecurityExpressionHandler instance could be found in the application " + "context. There must be at least one in order to support expressions in JSP 'authorize' tags." ) ;


signature:
public class UsernamePasswordAuthenticationTokenDeserializer { /** * This method construct { @ link UsernamePasswordAuthenticationToken } object from serialized json .
 * @ param jp the JsonParser
 * @ param ctxt the DeserializationContext
 * @ return the user
 * @ throws IOException if a exception during IO occurs
 * @ throws JsonProcessingException if an error during JSON processing occurs */
@ Override public UsernamePasswordAuthenticationToken deserialize ( JsonParser jp , DeserializationContext ctxt ) throws IOException , JsonProcessingException { } }

implementation: UsernamePasswordAuthenticationToken token = null ; ObjectMapper mapper = ( ObjectMapper ) jp . getCodec ( ) ; JsonNode jsonNode = mapper . readTree ( jp ) ; Boolean authenticated = readJsonNode ( jsonNode , "authenticated" ) . asBoolean ( ) ; JsonNode principalNode = readJsonNode ( jsonNode , "principal" ) ; Object principal = null ; if ( principalNode . isObject ( ) ) { principal = mapper . readValue ( principalNode . traverse ( mapper ) , Object . class ) ; } else { principal = principalNode . asText ( ) ; } JsonNode credentialsNode = readJsonNode ( jsonNode , "credentials" ) ; Object credentials ; if ( credentialsNode . isNull ( ) || credentialsNode . isMissingNode ( ) ) { credentials = null ; } else { credentials = credentialsNode . asText ( ) ; } List < GrantedAuthority > authorities = mapper . readValue ( readJsonNode ( jsonNode , "authorities" ) . traverse ( mapper ) , new TypeReference < List < GrantedAuthority > > ( ) { } ) ; if ( authenticated ) { token = new UsernamePasswordAuthenticationToken ( principal , credentials , authorities ) ; } else { token = new UsernamePasswordAuthenticationToken ( principal , credentials ) ; } JsonNode detailsNode = readJsonNode ( jsonNode , "details" ) ; if ( detailsNode . isNull ( ) || detailsNode . isMissingNode ( ) ) { token . setDetails ( null ) ; } else { token . setDetails ( detailsNode ) ; } return token ;


signature:
public class RememberMeConfigurer { /** * If available , initializes the { @ link DefaultLoginPageGeneratingFilter } shared
 * object .
 * @ param http the { @ link HttpSecurityBuilder } to use */
private void initDefaultLoginFilter ( H http ) { } }

implementation: DefaultLoginPageGeneratingFilter loginPageGeneratingFilter = http . getSharedObject ( DefaultLoginPageGeneratingFilter . class ) ; if ( loginPageGeneratingFilter != null ) { loginPageGeneratingFilter . setRememberMeParameter ( getRememberMeParameter ( ) ) ; }