Input: Creates an instance of { @link AuthorityReactiveAuthorizationManager } with the provided authorities . [CODESPLIT] public static < T > AuthorityReactiveAuthorizationManager < T > hasAnyRole ( String ... roles ) { Assert . notNull ( roles , "roles cannot be null" ) ; for ( String role : roles ) { Assert . notNull ( role , "role cannot be null" ) ; } return hasAnyAuthority ( Stream . of ( roles ) . map ( r -> "ROLE_" + r ) . toArray ( String [ ] :: new ) ) ; }


Input: Gets the security context for the current request ( if available ) and returns it . <p > If the session is null the context object is null or the context object stored in the session is not an instance of { [CODESPLIT] public SecurityContext loadContext ( HttpRequestResponseHolder requestResponseHolder ) { HttpServletRequest request = requestResponseHolder . getRequest ( ) ; HttpServletResponse response = requestResponseHolder . getResponse ( ) ; HttpSession httpSession = request . getSession ( false ) ; SecurityContext context = readSecurityContextFromSession ( httpSession ) ; if ( context == null ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "No SecurityContext was available from the HttpSession: " + httpSession + ". " + "A new one will be created." ) ; } context = generateNewContext ( ) ; } SaveToSessionResponseWrapper wrappedResponse = new SaveToSessionResponseWrapper ( response , request , httpSession != null , context ) ; requestResponseHolder . setResponse ( wrappedResponse ) ; requestResponseHolder . setRequest ( new SaveToSessionRequestWrapper ( request , wrappedResponse ) ) ; return context ; }


Input: Maps any request . [CODESPLIT] public C anyRequest ( ) { Assert . state ( ! this . anyRequestConfigured , "Can't configure anyRequest after itself" ) ; C configurer = requestMatchers ( ANY_REQUEST ) ; this . anyRequestConfigured = true ; return configurer ; }


Input: Maps a { @link List } of { @link org . springframework . security . web . util . matcher . AntPathRequestMatcher } instances that do not care which { @link HttpMethod } is used . [CODESPLIT] public C antMatchers ( String ... antPatterns ) { Assert . state ( ! this . anyRequestConfigured , "Can't configure antMatchers after anyRequest" ) ; return chainRequestMatchers ( RequestMatchers . antMatchers ( antPatterns ) ) ; }


Input: Creates { @link MvcRequestMatcher } instances for the method and patterns passed in [CODESPLIT] protected final List < MvcRequestMatcher > createMvcMatchers ( HttpMethod method , String ... mvcPatterns ) { Assert . state ( ! this . anyRequestConfigured , "Can't configure mvcMatchers after anyRequest" ) ; ObjectPostProcessor < Object > opp = this . context . getBean ( ObjectPostProcessor . class ) ; if ( ! this . context . containsBean ( HANDLER_MAPPING_INTROSPECTOR_BEAN_NAME ) ) { throw new NoSuchBeanDefinitionException ( "A Bean named " + HANDLER_MAPPING_INTROSPECTOR_BEAN_NAME + " of type " + HandlerMappingIntrospector . class . getName ( ) + " is required to use MvcRequestMatcher. Please ensure Spring Security & Spring MVC are configured in a shared ApplicationContext." ) ; } HandlerMappingIntrospector introspector = this . context . getBean ( HANDLER_MAPPING_INTROSPECTOR_BEAN_NAME , HandlerMappingIntrospector . class ) ; List < MvcRequestMatcher > matchers = new ArrayList <> ( mvcPatterns . length ) ; for ( String mvcPattern : mvcPatterns ) { MvcRequestMatcher matcher = new MvcRequestMatcher ( introspector , mvcPattern ) ; opp . postProcess ( matcher ) ; if ( method != null ) { matcher . setMethod ( method ) ; } matchers . add ( matcher ) ; } return matchers ; }


Input: Maps a { @link List } of { @link org . springframework . security . web . util . matcher . RegexRequestMatcher } instances . [CODESPLIT] public C regexMatchers ( HttpMethod method , String ... regexPatterns ) { Assert . state ( ! this . anyRequestConfigured , "Can't configure regexMatchers after anyRequest" ) ; return chainRequestMatchers ( RequestMatchers . regexMatchers ( method , regexPatterns ) ) ; }


Input: Associates a list of { @link RequestMatcher } instances with the { @link AbstractConfigAttributeRequestMatcherRegistry } [CODESPLIT] public C requestMatchers ( RequestMatcher ... requestMatchers ) { Assert . state ( ! this . anyRequestConfigured , "Can't configure requestMatchers after anyRequest" ) ; return chainRequestMatchers ( Arrays . asList ( requestMatchers ) ) ; }


Input: / * ( non - Javadoc ) [CODESPLIT] public Object resolveArgument ( MethodParameter parameter , Message < ? > message ) throws Exception { Authentication authentication = SecurityContextHolder . getContext ( ) . getAuthentication ( ) ; if ( authentication == null ) { return null ; } Object principal = authentication . getPrincipal ( ) ; AuthenticationPrincipal authPrincipal = findMethodAnnotation ( AuthenticationPrincipal . class , parameter ) ; String expressionToParse = authPrincipal . expression ( ) ; if ( StringUtils . hasLength ( expressionToParse ) ) { StandardEvaluationContext context = new StandardEvaluationContext ( ) ; context . setRootObject ( principal ) ; context . setVariable ( "this" , principal ) ; Expression expression = this . parser . parseExpression ( expressionToParse ) ; principal = expression . getValue ( context ) ; } if ( principal != null && ! parameter . getParameterType ( ) . isAssignableFrom ( principal . getClass ( ) ) ) { if ( authPrincipal . errorOnInvalidType ( ) ) { throw new ClassCastException ( principal + " is not assignable to " + parameter . getParameterType ( ) ) ; } else { return null ; } } return principal ; }


Input: Creates a LoginContext using the Configuration that was specified in { [CODESPLIT] @ Override protected LoginContext createLoginContext ( CallbackHandler handler ) throws LoginException { return new LoginContext ( getLoginContextName ( ) , null , handler , getConfiguration ( ) ) ; }


Input: ======================================================================================================== [CODESPLIT] public DirContextOperations authenticate ( Authentication authentication ) { DirContextOperations user = null ; Assert . isInstanceOf ( UsernamePasswordAuthenticationToken . class , authentication , "Can only process UsernamePasswordAuthenticationToken objects" ) ; String username = authentication . getName ( ) ; String password = ( String ) authentication . getCredentials ( ) ; if ( ! StringUtils . hasLength ( password ) ) { logger . debug ( "Rejecting empty password for user " + username ) ; throw new BadCredentialsException ( messages . getMessage ( "BindAuthenticator.emptyPassword" , "Empty Password" ) ) ; } // If DN patterns are configured, try authenticating with them directly for ( String dn : getUserDns ( username ) ) { user = bindWithDn ( dn , username , password ) ; if ( user != null ) { break ; } } // Otherwise use the configured search object to find the user and authenticate // with the returned DN. if ( user == null && getUserSearch ( ) != null ) { DirContextOperations userFromSearch = getUserSearch ( ) . searchForUser ( username ) ; user = bindWithDn ( userFromSearch . getDn ( ) . toString ( ) , username , password , userFromSearch . getAttributes ( ) ) ; } if ( user == null ) { throw new BadCredentialsException ( messages . getMessage ( "BindAuthenticator.badCredentials" , "Bad credentials" ) ) ; } return user ; }


Input: Allows subclasses to inspect the exception thrown by an attempt to bind with a particular DN . The default implementation just reports the failure to the debug logger . [CODESPLIT] protected void handleBindException ( String userDn , String username , Throwable cause ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Failed to bind as " + userDn + ": " + cause ) ; } }


Input: Returns the { @link RequestEntity } used for the UserInfo Request . [CODESPLIT] @ Override public RequestEntity < ? > convert ( OAuth2UserRequest userRequest ) { ClientRegistration clientRegistration = userRequest . getClientRegistration ( ) ; HttpMethod httpMethod = HttpMethod . GET ; if ( AuthenticationMethod . FORM . equals ( clientRegistration . getProviderDetails ( ) . getUserInfoEndpoint ( ) . getAuthenticationMethod ( ) ) ) { httpMethod = HttpMethod . POST ; } HttpHeaders headers = new HttpHeaders ( ) ; headers . setAccept ( Collections . singletonList ( MediaType . APPLICATION_JSON ) ) ; URI uri = UriComponentsBuilder . fromUriString ( clientRegistration . getProviderDetails ( ) . getUserInfoEndpoint ( ) . getUri ( ) ) . build ( ) . toUri ( ) ; RequestEntity < ? > request ; if ( HttpMethod . POST . equals ( httpMethod ) ) { headers . setContentType ( DEFAULT_CONTENT_TYPE ) ; MultiValueMap < String , String > formParameters = new LinkedMultiValueMap <> ( ) ; formParameters . add ( OAuth2ParameterNames . ACCESS_TOKEN , userRequest . getAccessToken ( ) . getTokenValue ( ) ) ; request = new RequestEntity <> ( formParameters , headers , httpMethod , uri ) ; } else { headers . setBearerAuth ( userRequest . getAccessToken ( ) . getTokenValue ( ) ) ; request = new RequestEntity <> ( headers , httpMethod , uri ) ; } return request ; }


Input: / * ( non - Javadoc ) [CODESPLIT] @ Override protected void doFilterInternal ( HttpServletRequest request , HttpServletResponse response , FilterChain filterChain ) throws ServletException , IOException { request . setAttribute ( HttpServletResponse . class . getName ( ) , response ) ; CsrfToken csrfToken = this . tokenRepository . loadToken ( request ) ; final boolean missingToken = csrfToken == null ; if ( missingToken ) { csrfToken = this . tokenRepository . generateToken ( request ) ; this . tokenRepository . saveToken ( csrfToken , request , response ) ; } request . setAttribute ( CsrfToken . class . getName ( ) , csrfToken ) ; request . setAttribute ( csrfToken . getParameterName ( ) , csrfToken ) ; if ( ! this . requireCsrfProtectionMatcher . matches ( request ) ) { filterChain . doFilter ( request , response ) ; return ; } String actualToken = request . getHeader ( csrfToken . getHeaderName ( ) ) ; if ( actualToken == null ) { actualToken = request . getParameter ( csrfToken . getParameterName ( ) ) ; } if ( ! csrfToken . getToken ( ) . equals ( actualToken ) ) { if ( this . logger . isDebugEnabled ( ) ) { this . logger . debug ( "Invalid CSRF token found for " + UrlUtils . buildFullRequestUrl ( request ) ) ; } if ( missingToken ) { this . accessDeniedHandler . handle ( request , response , new MissingCsrfTokenException ( actualToken ) ) ; } else { this . accessDeniedHandler . handle ( request , response , new InvalidCsrfTokenException ( csrfToken , actualToken ) ) ; } return ; } filterChain . doFilter ( request , response ) ; }


Input: / * ( non - Javadoc ) [CODESPLIT] public void onAuthentication ( Authentication authentication , HttpServletRequest request , HttpServletResponse response ) throws SessionAuthenticationException { for ( SessionAuthenticationStrategy delegate : this . delegateStrategies ) { if ( this . logger . isDebugEnabled ( ) ) { this . logger . debug ( "Delegating to " + delegate ) ; } delegate . onAuthentication ( authentication , request , response ) ; } }


Input: Builds list of possible DNs for the user worked out from the <tt > userDnPatterns< / tt > property . [CODESPLIT] protected List < String > getUserDns ( String username ) { if ( userDnFormat == null ) { return Collections . emptyList ( ) ; } List < String > userDns = new ArrayList <> ( userDnFormat . length ) ; String [ ] args = new String [ ] { LdapEncoder . nameEncode ( username ) } ; synchronized ( userDnFormat ) { for ( MessageFormat formatter : userDnFormat ) { userDns . add ( formatter . format ( args ) ) ; } } return userDns ; }


Input: Sets the pattern which will be used to supply a DN for the user . The pattern should be the name relative to the root DN . The pattern argument { 0 } will contain the username . An example would be cn = { 0 } ou = people . [CODESPLIT] public void setUserDnPatterns ( String [ ] dnPattern ) { Assert . notNull ( dnPattern , "The array of DN patterns cannot be set to null" ) ; // this.userDnPattern = dnPattern; userDnFormat = new MessageFormat [ dnPattern . length ] ; for ( int i = 0 ; i < dnPattern . length ; i ++ ) { userDnFormat [ i ] = new MessageFormat ( dnPattern [ i ] ) ; } }


Input: ======================================================================================================== [CODESPLIT] public void onApplicationEvent ( AbstractAuthorizationEvent event ) { if ( event instanceof AuthenticationCredentialsNotFoundEvent ) { AuthenticationCredentialsNotFoundEvent authEvent = ( AuthenticationCredentialsNotFoundEvent ) event ; if ( logger . isWarnEnabled ( ) ) { logger . warn ( "Security interception failed due to: " + authEvent . getCredentialsNotFoundException ( ) + "; secure object: " + authEvent . getSource ( ) + "; configuration attributes: " + authEvent . getConfigAttributes ( ) ) ; } } if ( event instanceof AuthorizationFailureEvent ) { AuthorizationFailureEvent authEvent = ( AuthorizationFailureEvent ) event ; if ( logger . isWarnEnabled ( ) ) { logger . warn ( "Security authorization failed due to: " + authEvent . getAccessDeniedException ( ) + "; authenticated principal: " + authEvent . getAuthentication ( ) + "; secure object: " + authEvent . getSource ( ) + "; configuration attributes: " + authEvent . getConfigAttributes ( ) ) ; } } if ( event instanceof AuthorizedEvent ) { AuthorizedEvent authEvent = ( AuthorizedEvent ) event ; if ( logger . isInfoEnabled ( ) ) { logger . info ( "Security authorized for authenticated principal: " + authEvent . getAuthentication ( ) + "; secure object: " + authEvent . getSource ( ) + "; configuration attributes: " + authEvent . getConfigAttributes ( ) ) ; } } if ( event instanceof PublicInvocationEvent ) { PublicInvocationEvent authEvent = ( PublicInvocationEvent ) event ; if ( logger . isInfoEnabled ( ) ) { logger . info ( "Security interception not required for public secure object: " + authEvent . getSource ( ) ) ; } } }


Input: Creates the mapping of { @link RequestMatcher } to { @link Collection } of { @link ConfigAttribute } instances [CODESPLIT] final LinkedHashMap < RequestMatcher , Collection < ConfigAttribute > > createRequestMap ( ) { if ( unmappedMatchers != null ) { throw new IllegalStateException ( "An incomplete mapping was found for " + unmappedMatchers + ". Try completing it with something like requestUrls().<something>.hasRole('USER')" ) ; } LinkedHashMap < RequestMatcher , Collection < ConfigAttribute > > requestMap = new LinkedHashMap < RequestMatcher , Collection < ConfigAttribute > > ( ) ; for ( UrlMapping mapping : getUrlMappings ( ) ) { RequestMatcher matcher = mapping . getRequestMatcher ( ) ; Collection < ConfigAttribute > configAttrs = mapping . getConfigAttrs ( ) ; requestMap . put ( matcher , configAttrs ) ; } return requestMap ; }


Input: Implementation of { [CODESPLIT] public void onLogoutSuccess ( HttpServletRequest request , HttpServletResponse response , Authentication authentication ) throws IOException , ServletException { response . setStatus ( this . httpStatusToReturn . value ( ) ) ; response . getWriter ( ) . flush ( ) ; }


Input: Determines whether the user represented by the supplied <tt > Authentication< / tt > object is allowed to invoke the supplied URI . [CODESPLIT] public boolean isAllowed ( String uri , Authentication authentication ) { return isAllowed ( null , uri , null , authentication ) ; }


Input: Determines whether the user represented by the supplied <tt > Authentication< / tt > object is allowed to invoke the supplied URI with the given . <p > Note the default implementation of <tt > FilterInvocationSecurityMetadataSource< / tt > disregards the <code > contextPath< / code > when evaluating which secure object metadata applies to a given request URI so generally the <code > contextPath< / code > is unimportant unless you are using a custom <code > FilterInvocationSecurityMetadataSource< / code > . [CODESPLIT] public boolean isAllowed ( String contextPath , String uri , String method , Authentication authentication ) { Assert . notNull ( uri , "uri parameter is required" ) ; FilterInvocation fi = new FilterInvocation ( contextPath , uri , method ) ; Collection < ConfigAttribute > attrs = securityInterceptor . obtainSecurityMetadataSource ( ) . getAttributes ( fi ) ; if ( attrs == null ) { if ( securityInterceptor . isRejectPublicInvocations ( ) ) { return false ; } return true ; } if ( authentication == null ) { return false ; } try { securityInterceptor . getAccessDecisionManager ( ) . decide ( authentication , fi , attrs ) ; } catch ( AccessDeniedException unauthorized ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( fi . toString ( ) + " denied for " + authentication . toString ( ) , unauthorized ) ; } return false ; } return true ; }


Input: / * ( non - Javadoc ) [CODESPLIT] @ Override public Map < String , String > extractUriTemplateVariables ( HttpServletRequest request ) { MatchableHandlerMapping mapping = getMapping ( request ) ; if ( mapping == null ) { return this . defaultMatcher . extractUriTemplateVariables ( request ) ; } RequestMatchResult result = mapping . match ( request , this . pattern ) ; return result == null ? Collections . < String , String > emptyMap ( ) : result . extractUriTemplateVariables ( ) ; }


Input: Initialize the target URL . It allows for the host to change based upon the cas . service . host system property . If the property is not set the default is localhost : 8443 . [CODESPLIT] @ Override public void init ( ) throws ServletException { super . init ( ) ; String casServiceHost = System . getProperty ( "cas.service.host" , "localhost:8443" ) ; targetUrl = "https://" + casServiceHost + "/cas-sample/secure/" ; }


Input: ======================================================================================================== [CODESPLIT] @ Override public long getDateHeader ( String name ) { String value = getHeader ( name ) ; if ( value == null ) { return - 1L ; } // Attempt to convert the date header in a variety of formats long result = FastHttpDateFormat . parseDate ( value , formats ) ; if ( result != - 1L ) { return result ; } throw new IllegalArgumentException ( value ) ; }


Input: If the parameter is available from the wrapped request then the request has been forwarded / included to a URL with parameters either supplementing or overriding the saved request values . <p > In this case the value from the wrapped request should be used . <p > If the value from the wrapped request is null an attempt will be made to retrieve the parameter from the saved request . [CODESPLIT] @ Override public String getParameter ( String name ) { String value = super . getParameter ( name ) ; if ( value != null ) { return value ; } String [ ] values = savedRequest . getParameterValues ( name ) ; if ( values == null || values . length == 0 ) { return null ; } return values [ 0 ] ; }


Input: Read and returns the variable named by { @code principalEnvironmentVariable } from the request . [CODESPLIT] protected Object getPreAuthenticatedPrincipal ( HttpServletRequest request ) { String principal = ( String ) request . getAttribute ( principalEnvironmentVariable ) ; if ( principal == null && exceptionIfVariableMissing ) { throw new PreAuthenticatedCredentialsNotFoundException ( principalEnvironmentVariable + " variable not found in request." ) ; } return principal ; }


Input: In addition to the steps from the superclass the sessionRegistry will be updated with the new session information . [CODESPLIT] public void onAuthentication ( Authentication authentication , HttpServletRequest request , HttpServletResponse response ) { sessionRegistry . registerNewSession ( request . getSession ( ) . getId ( ) , authentication . getPrincipal ( ) ) ; }


Input: This method should be used to enforce security on a <code > MethodInvocation< / code > . [CODESPLIT] public Object invoke ( MethodInvocation mi ) throws Throwable { InterceptorStatusToken token = super . beforeInvocation ( mi ) ; Object result ; try { result = mi . proceed ( ) ; } finally { super . finallyInvocation ( token ) ; } return super . afterInvocation ( token , result ) ; }


Input: This is a public method . [CODESPLIT] @ Transactional ( readOnly = true ) public Contact getRandomContact ( ) { logger . debug ( "Returning random contact" ) ; Random rnd = new Random ( ) ; List < Contact > contacts = contactDao . findAll ( ) ; int getNumber = rnd . nextInt ( contacts . size ( ) ) ; return contacts . get ( getNumber ) ; }


Input: ======================================================================================================== [CODESPLIT] public void evictFromCache ( Serializable pk ) { Assert . notNull ( pk , "Primary key (identifier) required" ) ; MutableAcl acl = getFromCache ( pk ) ; if ( acl != null ) { cache . remove ( acl . getId ( ) ) ; cache . remove ( acl . getObjectIdentity ( ) ) ; } }


Input: Performs post processing of an object . The default is to delegate to the { @link ObjectPostProcessor } . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) protected < T > T postProcess ( T object ) { return ( T ) this . objectPostProcessor . postProcess ( object ) ; }


Input: Calls the parent class { [CODESPLIT] public void onAuthenticationSuccess ( HttpServletRequest request , HttpServletResponse response , Authentication authentication ) throws IOException , ServletException { handle ( request , response , authentication ) ; clearAuthenticationAttributes ( request ) ; }


Input: Removes temporary authentication - related data which may have been stored in the session during the authentication process . [CODESPLIT] protected final void clearAuthenticationAttributes ( HttpServletRequest request ) { HttpSession session = request . getSession ( false ) ; if ( session == null ) { return ; } session . removeAttribute ( WebAttributes . AUTHENTICATION_EXCEPTION ) ; }


Input: Attempts to locate the specified field on the class . [CODESPLIT] public static Field getField ( Class < ? > clazz , String fieldName ) throws IllegalStateException { Assert . notNull ( clazz , "Class required" ) ; Assert . hasText ( fieldName , "Field name required" ) ; try { return clazz . getDeclaredField ( fieldName ) ; } catch ( NoSuchFieldException nsf ) { // Try superclass if ( clazz . getSuperclass ( ) != null ) { return getField ( clazz . getSuperclass ( ) , fieldName ) ; } throw new IllegalStateException ( "Could not locate field '" + fieldName + "' on class " + clazz ) ; } }


Input: Returns the value of a ( nested ) field on a bean . Intended for testing . [CODESPLIT] public static Object getFieldValue ( Object bean , String fieldName ) throws IllegalAccessException { Assert . notNull ( bean , "Bean cannot be null" ) ; Assert . hasText ( fieldName , "Field name required" ) ; String [ ] nestedFields = StringUtils . tokenizeToStringArray ( fieldName , "." ) ; Class < ? > componentClass = bean . getClass ( ) ; Object value = bean ; for ( String nestedField : nestedFields ) { Field field = getField ( componentClass , nestedField ) ; field . setAccessible ( true ) ; value = field . get ( value ) ; if ( value != null ) { componentClass = value . getClass ( ) ; } } return value ; }


Input: ======================================================================================================== [CODESPLIT] public void afterPropertiesSet ( ) throws Exception { Assert . hasLength ( this . loginUrl , "loginUrl must be specified" ) ; Assert . notNull ( this . serviceProperties , "serviceProperties must be specified" ) ; Assert . notNull ( this . serviceProperties . getService ( ) , "serviceProperties.getService() cannot be null." ) ; }


Input: Constructs a new Service Url . The default implementation relies on the CAS client to do the bulk of the work . [CODESPLIT] protected String createServiceUrl ( final HttpServletRequest request , final HttpServletResponse response ) { return CommonUtils . constructServiceUrl ( null , response , this . serviceProperties . getService ( ) , null , this . serviceProperties . getArtifactParameter ( ) , this . encodeServiceUrlWithSessionId ) ; }


Input: Constructs the Url for Redirection to the CAS server . Default implementation relies on the CAS client to do the bulk of the work . [CODESPLIT] protected String createRedirectUrl ( final String serviceUrl ) { return CommonUtils . constructRedirectUrl ( this . loginUrl , this . serviceProperties . getServiceParameter ( ) , serviceUrl , this . serviceProperties . isSendRenew ( ) , false ) ; }


Input: Set the role hierarchy and pre - calculate for every role the set of all reachable roles i . e . all roles lower in the hierarchy of every given role . Pre - calculation is done for performance reasons ( reachable roles can then be calculated in O ( 1 ) time ) . During pre - calculation cycles in role hierarchy are detected and will cause a <tt > CycleInRoleHierarchyException< / tt > to be thrown . [CODESPLIT] public void setHierarchy ( String roleHierarchyStringRepresentation ) { this . roleHierarchyStringRepresentation = roleHierarchyStringRepresentation ; logger . debug ( "setHierarchy() - The following role hierarchy was set: " + roleHierarchyStringRepresentation ) ; buildRolesReachableInOneStepMap ( ) ; buildRolesReachableInOneOrMoreStepsMap ( ) ; }


Input: SEC - 863 [CODESPLIT] private void addReachableRoles ( Set < GrantedAuthority > reachableRoles , GrantedAuthority authority ) { for ( GrantedAuthority testAuthority : reachableRoles ) { String testKey = testAuthority . getAuthority ( ) ; if ( ( testKey != null ) && ( testKey . equals ( authority . getAuthority ( ) ) ) ) { return ; } } reachableRoles . add ( authority ) ; }


Input: SEC - 863 [CODESPLIT] private Set < GrantedAuthority > getRolesReachableInOneOrMoreSteps ( GrantedAuthority authority ) { if ( authority . getAuthority ( ) == null ) { return null ; } for ( GrantedAuthority testAuthority : this . rolesReachableInOneOrMoreStepsMap . keySet ( ) ) { String testKey = testAuthority . getAuthority ( ) ; if ( ( testKey != null ) && ( testKey . equals ( authority . getAuthority ( ) ) ) ) { return this . rolesReachableInOneOrMoreStepsMap . get ( testAuthority ) ; } } return null ; }


Input: Parse input and build the map for the roles reachable in one step : the higher role will become a key that references a set of the reachable lower roles . [CODESPLIT] private void buildRolesReachableInOneStepMap ( ) { this . rolesReachableInOneStepMap = new HashMap < GrantedAuthority , Set < GrantedAuthority > > ( ) ; try ( BufferedReader bufferedReader = new BufferedReader ( new StringReader ( this . roleHierarchyStringRepresentation ) ) ) { for ( String readLine ; ( readLine = bufferedReader . readLine ( ) ) != null ; ) { String [ ] roles = readLine . split ( " > " ) ; for ( int i = 1 ; i < roles . length ; i ++ ) { GrantedAuthority higherRole = new SimpleGrantedAuthority ( roles [ i - 1 ] . replaceAll ( "^\\s+|\\s+$" , "" ) ) ; GrantedAuthority lowerRole = new SimpleGrantedAuthority ( roles [ i ] . replaceAll ( "^\\s+|\\s+$" , "" ) ) ; Set < GrantedAuthority > rolesReachableInOneStepSet ; if ( ! this . rolesReachableInOneStepMap . containsKey ( higherRole ) ) { rolesReachableInOneStepSet = new HashSet < GrantedAuthority > ( ) ; this . rolesReachableInOneStepMap . put ( higherRole , rolesReachableInOneStepSet ) ; } else { rolesReachableInOneStepSet = this . rolesReachableInOneStepMap . get ( higherRole ) ; } addReachableRoles ( rolesReachableInOneStepSet , lowerRole ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "buildRolesReachableInOneStepMap() - From role " + higherRole + " one can reach role " + lowerRole + " in one step." ) ; } } } } catch ( IOException e ) { throw new IllegalStateException ( e ) ; } }


Input: For every higher role from rolesReachableInOneStepMap store all roles that are reachable from it in the map of roles reachable in one or more steps . ( Or throw a CycleInRoleHierarchyException if a cycle in the role hierarchy definition is detected ) [CODESPLIT] private void buildRolesReachableInOneOrMoreStepsMap ( ) { this . rolesReachableInOneOrMoreStepsMap = new HashMap <> ( ) ; // iterate over all higher roles from rolesReachableInOneStepMap for ( GrantedAuthority role : this . rolesReachableInOneStepMap . keySet ( ) ) { Set < GrantedAuthority > rolesToVisitSet = new HashSet <> ( ) ; if ( this . rolesReachableInOneStepMap . containsKey ( role ) ) { rolesToVisitSet . addAll ( this . rolesReachableInOneStepMap . get ( role ) ) ; } Set < GrantedAuthority > visitedRolesSet = new HashSet <> ( ) ; while ( ! rolesToVisitSet . isEmpty ( ) ) { // take a role from the rolesToVisit set GrantedAuthority aRole = rolesToVisitSet . iterator ( ) . next ( ) ; rolesToVisitSet . remove ( aRole ) ; addReachableRoles ( visitedRolesSet , aRole ) ; if ( this . rolesReachableInOneStepMap . containsKey ( aRole ) ) { Set < GrantedAuthority > newReachableRoles = this . rolesReachableInOneStepMap . get ( aRole ) ; // definition of a cycle: you can reach the role you are starting from if ( rolesToVisitSet . contains ( role ) || visitedRolesSet . contains ( role ) ) { throw new CycleInRoleHierarchyException ( ) ; } else { // no cycle rolesToVisitSet . addAll ( newReachableRoles ) ; } } } this . rolesReachableInOneOrMoreStepsMap . put ( role , visitedRolesSet ) ; logger . debug ( "buildRolesReachableInOneOrMoreStepsMap() - From role " + role + " one can reach " + visitedRolesSet + " in one or more steps." ) ; } }


Input: internal helpers [CODESPLIT] private byte [ ] iv ( byte [ ] encrypted ) { return this . ivGenerator != NULL_IV_GENERATOR ? subArray ( encrypted , 0 , this . ivGenerator . getKeyLength ( ) ) : NULL_IV_GENERATOR . generateKey ( ) ; }


Input: Adds a { @link LogoutHandler } . The { @link SecurityContextLogoutHandler } is added as the last { @link LogoutHandler } by default . [CODESPLIT] public LogoutConfigurer < H > addLogoutHandler ( LogoutHandler logoutHandler ) { Assert . notNull ( logoutHandler , "logoutHandler cannot be null" ) ; this . logoutHandlers . add ( logoutHandler ) ; return this ; }


Input: Sets the { @link LogoutSuccessHandler } to use . If this is specified { @link #logoutSuccessUrl ( String ) } is ignored . [CODESPLIT] public LogoutConfigurer < H > logoutSuccessHandler ( LogoutSuccessHandler logoutSuccessHandler ) { this . logoutSuccessUrl = null ; this . customLogoutSuccess = true ; this . logoutSuccessHandler = logoutSuccessHandler ; return this ; }


Input: Sets a default { @link LogoutSuccessHandler } to be used which prefers being invoked for the provided { @link RequestMatcher } . If no { @link LogoutSuccessHandler } is specified a { @link SimpleUrlLogoutSuccessHandler } will be used . If any default { @link LogoutSuccessHandler } instances are configured then a { @link DelegatingLogoutSuccessHandler } will be used that defaults to a { @link SimpleUrlLogoutSuccessHandler } . [CODESPLIT] public LogoutConfigurer < H > defaultLogoutSuccessHandlerFor ( LogoutSuccessHandler handler , RequestMatcher preferredMatcher ) { Assert . notNull ( handler , "handler cannot be null" ) ; Assert . notNull ( preferredMatcher , "preferredMatcher cannot be null" ) ; this . defaultLogoutSuccessHandlerMappings . put ( preferredMatcher , handler ) ; return this ; }


Input: Gets the { @link LogoutSuccessHandler } if not null otherwise creates a new { @link SimpleUrlLogoutSuccessHandler } using the { @link #logoutSuccessUrl ( String ) } . [CODESPLIT] private LogoutSuccessHandler getLogoutSuccessHandler ( ) { LogoutSuccessHandler handler = this . logoutSuccessHandler ; if ( handler == null ) { handler = createDefaultSuccessHandler ( ) ; } return handler ; }


Input: Creates the { @link LogoutFilter } using the { @link LogoutHandler } instances the { @link #logoutSuccessHandler ( LogoutSuccessHandler ) } and the { @link #logoutUrl ( String ) } . [CODESPLIT] private LogoutFilter createLogoutFilter ( H http ) throws Exception { logoutHandlers . add ( contextLogoutHandler ) ; LogoutHandler [ ] handlers = logoutHandlers . toArray ( new LogoutHandler [ logoutHandlers . size ( ) ] ) ; LogoutFilter result = new LogoutFilter ( getLogoutSuccessHandler ( ) , handlers ) ; result . setLogoutRequestMatcher ( getLogoutRequestMatcher ( http ) ) ; result = postProcess ( result ) ; return result ; }


Input: ======================================================================================================== [CODESPLIT] public Collection < ConfigAttribute > getAttributes ( Method method , Class < ? > targetClass ) { DefaultCacheKey cacheKey = new DefaultCacheKey ( method , targetClass ) ; synchronized ( attributeCache ) { Collection < ConfigAttribute > cached = attributeCache . get ( cacheKey ) ; // Check for canonical value indicating there is no config attribute, if ( cached != null ) { return cached ; } // No cached value, so query the sources to find a result Collection < ConfigAttribute > attributes = null ; for ( MethodSecurityMetadataSource s : methodSecurityMetadataSources ) { attributes = s . getAttributes ( method , targetClass ) ; if ( attributes != null && ! attributes . isEmpty ( ) ) { break ; } } // Put it in the cache. if ( attributes == null || attributes . isEmpty ( ) ) { this . attributeCache . put ( cacheKey , NULL_CONFIG_ATTRIBUTE ) ; return NULL_CONFIG_ATTRIBUTE ; } if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Caching method [" + cacheKey + "] with attributes " + attributes ) ; } this . attributeCache . put ( cacheKey , attributes ) ; return attributes ; } }


Input: ======================================================================================================== [CODESPLIT] private byte [ ] combineHashAndSalt ( byte [ ] hash , byte [ ] salt ) { if ( salt == null ) { return hash ; } byte [ ] hashAndSalt = new byte [ hash . length + salt . length ] ; System . arraycopy ( hash , 0 , hashAndSalt , 0 , hash . length ) ; System . arraycopy ( salt , 0 , hashAndSalt , hash . length , salt . length ) ; return hashAndSalt ; }


Input: Calculates the hash of password ( and salt bytes if supplied ) and returns a base64 encoded concatenation of the hash and salt prefixed with { SHA } ( or { SSHA } if salt was used ) . [CODESPLIT] public String encode ( CharSequence rawPass ) { byte [ ] salt = this . saltGenerator . generateKey ( ) ; return encode ( rawPass , salt ) ; }


Input: Checks the validity of an unencoded password against an encoded one in the form { SSHA } sQuQF8vj8Eg2Y1hPdh3bkQhCKQBgjhQI . [CODESPLIT] public boolean matches ( CharSequence rawPassword , String encodedPassword ) { return matches ( rawPassword == null ? null : rawPassword . toString ( ) , encodedPassword ) ; }


Input: Returns the hash prefix or null if there isn t one . [CODESPLIT] private String extractPrefix ( String encPass ) { if ( ! encPass . startsWith ( "{" ) ) { return null ; } int secondBrace = encPass . lastIndexOf ( ' ' ) ; if ( secondBrace < 0 ) { throw new IllegalArgumentException ( "Couldn't find closing brace for SHA prefix" ) ; } return encPass . substring ( 0 , secondBrace + 1 ) ; }


Input: Demonstrates that { @link HttpServletRequest#authenticate ( HttpServletResponse ) } will send the user to the log in page configured within Spring Security if the user is not already authenticated . [CODESPLIT] @ RequestMapping ( "/authenticate" ) public String authenticate ( HttpServletRequest request , HttpServletResponse response ) throws ServletException , IOException { boolean authenticate = request . authenticate ( response ) ; return authenticate ? "index" : null ; }


Input: Demonstrates that you can authenticate with Spring Security using { @link HttpServletRequest#login ( String String ) } . [CODESPLIT] @ RequestMapping ( value = "/login" , method = RequestMethod . POST ) public String login ( HttpServletRequest request , HttpServletResponse response , @ ModelAttribute LoginForm loginForm , BindingResult result ) throws ServletException { try { request . login ( loginForm . getUsername ( ) , loginForm . getPassword ( ) ) ; } catch ( ServletException authenticationFailed ) { result . rejectValue ( null , "authentication.failed" , authenticationFailed . getMessage ( ) ) ; return "login" ; } return "redirect:/" ; }


Input: Demonstrates that invoking { [CODESPLIT] @ RequestMapping ( "/logout" ) public String logout ( HttpServletRequest request , HttpServletResponse response , RedirectAttributes redirect ) throws ServletException { request . logout ( ) ; return "redirect:/" ; }


Input: Demonstrates Spring Security with { [CODESPLIT] @ RequestMapping ( "/async" ) public void asynch ( HttpServletRequest request , HttpServletResponse response ) { final AsyncContext async = request . startAsync ( ) ; async . start ( new Runnable ( ) { public void run ( ) { Authentication authentication = SecurityContextHolder . getContext ( ) . getAuthentication ( ) ; try { final HttpServletResponse asyncResponse = ( HttpServletResponse ) async . getResponse ( ) ; asyncResponse . setStatus ( HttpServletResponse . SC_OK ) ; asyncResponse . getWriter ( ) . write ( String . valueOf ( authentication ) ) ; async . complete ( ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } } } ) ; }


Input: Always returns a 403 error code to the client . [CODESPLIT] public void commence ( HttpServletRequest request , HttpServletResponse response , AuthenticationException arg2 ) throws IOException , ServletException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Pre-authenticated entry point called. Rejecting access" ) ; } response . sendError ( HttpServletResponse . SC_FORBIDDEN , "Access Denied" ) ; }


Input: ======================================================================================================== [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public Object decide ( Authentication authentication , Object object , Collection < ConfigAttribute > config , Object returnedObject ) throws AccessDeniedException { if ( returnedObject == null ) { logger . debug ( "Return object is null, skipping" ) ; return null ; } for ( ConfigAttribute attr : config ) { if ( ! this . supports ( attr ) ) { continue ; } // Need to process the Collection for this invocation Filterer filterer ; if ( returnedObject instanceof Collection ) { filterer = new CollectionFilterer ( ( Collection ) returnedObject ) ; } else if ( returnedObject . getClass ( ) . isArray ( ) ) { filterer = new ArrayFilterer ( ( Object [ ] ) returnedObject ) ; } else { throw new AuthorizationServiceException ( "A Collection or an array (or null) was required as the " + "returnedObject, but the returnedObject was: " + returnedObject ) ; } // Locate unauthorised Collection elements for ( Object domainObject : filterer ) { // Ignore nulls or entries which aren't instances of the configured domain // object class if ( domainObject == null || ! getProcessDomainObjectClass ( ) . isAssignableFrom ( domainObject . getClass ( ) ) ) { continue ; } if ( ! hasPermission ( authentication , domainObject ) ) { filterer . remove ( domainObject ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Principal is NOT authorised for element: " + domainObject ) ; } } } return filterer . getFilteredObject ( ) ; } return returnedObject ; }


Input: Checks whether a path is normalized ( doesn t contain path traversal sequences like . / / .. / or / . ) [CODESPLIT] private boolean isNormalized ( String path ) { if ( path == null ) { return true ; } for ( int j = path . length ( ) ; j > 0 ; ) { int i = path . lastIndexOf ( ' ' , j - 1 ) ; int gap = j - i ; if ( gap == 2 && path . charAt ( i + 1 ) == ' ' ) { // ".", "/./" or "/." return false ; } else if ( gap == 3 && path . charAt ( i + 1 ) == ' ' && path . charAt ( i + 2 ) == ' ' ) { return false ; } j = i ; } return true ; }


Input: Checks the filter list for possible errors and logs them [CODESPLIT] private void checkFilterStack ( List < Filter > filters ) { checkForDuplicates ( SecurityContextPersistenceFilter . class , filters ) ; checkForDuplicates ( UsernamePasswordAuthenticationFilter . class , filters ) ; checkForDuplicates ( SessionManagementFilter . class , filters ) ; checkForDuplicates ( BasicAuthenticationFilter . class , filters ) ; checkForDuplicates ( SecurityContextHolderAwareRequestFilter . class , filters ) ; checkForDuplicates ( JaasApiIntegrationFilter . class , filters ) ; checkForDuplicates ( ExceptionTranslationFilter . class , filters ) ; checkForDuplicates ( FilterSecurityInterceptor . class , filters ) ; }


Input: / * Checks for the common error of having a login page URL protected by the security interceptor [CODESPLIT] private void checkLoginPageIsntProtected ( FilterChainProxy fcp , List < Filter > filterStack ) { ExceptionTranslationFilter etf = getFilter ( ExceptionTranslationFilter . class , filterStack ) ; if ( etf == null || ! ( etf . getAuthenticationEntryPoint ( ) instanceof LoginUrlAuthenticationEntryPoint ) ) { return ; } String loginPage = ( ( LoginUrlAuthenticationEntryPoint ) etf . getAuthenticationEntryPoint ( ) ) . getLoginFormUrl ( ) ; logger . info ( "Checking whether login URL '" + loginPage + "' is accessible with your configuration" ) ; FilterInvocation loginRequest = new FilterInvocation ( loginPage , "POST" ) ; List < Filter > filters = null ; try { filters = fcp . getFilters ( loginPage ) ; } catch ( Exception e ) { // May happen legitimately if a filter-chain request matcher requires more // request data than that provided // by the dummy request used when creating the filter invocation. logger . info ( "Failed to obtain filter chain information for the login page. Unable to complete check." ) ; } if ( filters == null || filters . isEmpty ( ) ) { logger . debug ( "Filter chain is empty for the login page" ) ; return ; } if ( getFilter ( DefaultLoginPageGeneratingFilter . class , filters ) != null ) { logger . debug ( "Default generated login page is in use" ) ; return ; } FilterSecurityInterceptor fsi = getFilter ( FilterSecurityInterceptor . class , filters ) ; FilterInvocationSecurityMetadataSource fids = fsi . getSecurityMetadataSource ( ) ; Collection < ConfigAttribute > attributes = fids . getAttributes ( loginRequest ) ; if ( attributes == null ) { logger . debug ( "No access attributes defined for login page URL" ) ; if ( fsi . isRejectPublicInvocations ( ) ) { logger . warn ( "FilterSecurityInterceptor is configured to reject public invocations." + " Your login page may not be accessible." ) ; } return ; } AnonymousAuthenticationFilter anonPF = getFilter ( AnonymousAuthenticationFilter . class , filters ) ; if ( anonPF == null ) { logger . warn ( "The login page is being protected by the filter chain, but you don't appear to have" + " anonymous authentication enabled. This is almost certainly an error." ) ; return ; } // Simulate an anonymous access with the supplied attributes. AnonymousAuthenticationToken token = new AnonymousAuthenticationToken ( "key" , anonPF . getPrincipal ( ) , anonPF . getAuthorities ( ) ) ; try { fsi . getAccessDecisionManager ( ) . decide ( token , loginRequest , attributes ) ; } catch ( AccessDeniedException e ) { logger . warn ( "Anonymous access to the login page doesn't appear to be enabled. This is almost certainly " + "an error. Please check your configuration allows unauthenticated access to the configured " + "login page. (Simulated access was rejected: " + e + ")" ) ; } catch ( Exception e ) { // May happen legitimately if a filter-chain request matcher requires more // request data than that provided // by the dummy request used when creating the filter invocation. See SEC-1878 logger . info ( "Unable to check access to the login page to determine if anonymous access is allowed. This might be an error, but can happen under normal circumstances." , e ) ; } }


Input: Registers a <code > ThrowableCauseExtractor< / code > for the specified type . <i > Can be used in subclasses overriding { @link #initExtractorMap () } . < / i > [CODESPLIT] protected final void registerExtractor ( Class < ? extends Throwable > throwableType , ThrowableCauseExtractor extractor ) { Assert . notNull ( extractor , "Invalid extractor: null" ) ; this . extractorMap . put ( throwableType , extractor ) ; }


Input: Returns an array containing the classes for which extractors are registered . The order of the classes is the order in which comparisons will occur for resolving a matching extractor . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) final Class < ? extends Throwable > [ ] getRegisteredTypes ( ) { Set < Class < ? extends Throwable > > typeList = this . extractorMap . keySet ( ) ; return typeList . toArray ( new Class [ typeList . size ( ) ] ) ; }


Input: Determines the cause chain of the provided <code > Throwable< / code > . The returned array contains all throwables extracted from the stacktrace using the registered { @link ThrowableCauseExtractor extractors } . The elements of the array are ordered : The first element is the passed in throwable itself . The following elements appear in their order downward the stacktrace . <p > Note : If no { @link ThrowableCauseExtractor } is registered for this instance then the returned array will always only contain the passed in throwable . [CODESPLIT] public final Throwable [ ] determineCauseChain ( Throwable throwable ) { if ( throwable == null ) { throw new IllegalArgumentException ( "Invalid throwable: null" ) ; } List < Throwable > chain = new ArrayList <> ( ) ; Throwable currentThrowable = throwable ; while ( currentThrowable != null ) { chain . add ( currentThrowable ) ; currentThrowable = extractCause ( currentThrowable ) ; } return chain . toArray ( new Throwable [ chain . size ( ) ] ) ; }


Input: Extracts the cause of the given throwable using an appropriate extractor . [CODESPLIT] private Throwable extractCause ( Throwable throwable ) { for ( Map . Entry < Class < ? extends Throwable > , ThrowableCauseExtractor > entry : extractorMap . entrySet ( ) ) { Class < ? extends Throwable > throwableType = entry . getKey ( ) ; if ( throwableType . isInstance ( throwable ) ) { ThrowableCauseExtractor extractor = entry . getValue ( ) ; return extractor . extractCause ( throwable ) ; } } return null ; }


Input: Returns the first throwable from the passed in array that is assignable to the provided type . A returned instance is safe to be cast to the specified type . <p > If the passed in array is null or empty this method returns <code > null< / code > . [CODESPLIT] public final Throwable getFirstThrowableOfType ( Class < ? extends Throwable > throwableType , Throwable [ ] chain ) { if ( chain != null ) { for ( Throwable t : chain ) { if ( ( t != null ) && throwableType . isInstance ( t ) ) { return t ; } } } return null ; }


Input: Verifies that the provided throwable is a valid subclass of the provided type ( or of the type itself ) . If <code > expectdBaseType< / code > is <code > null< / code > no check will be performed . <p > Can be used for verification purposes in implementations of { @link ThrowableCauseExtractor extractors } . [CODESPLIT] public static void verifyThrowableHierarchy ( Throwable throwable , Class < ? extends Throwable > expectedBaseType ) { if ( expectedBaseType == null ) { return ; } if ( throwable == null ) { throw new IllegalArgumentException ( "Invalid throwable: null" ) ; } Class < ? extends Throwable > throwableType = throwable . getClass ( ) ; if ( ! expectedBaseType . isAssignableFrom ( throwableType ) ) { throw new IllegalArgumentException ( "Invalid type: '" + throwableType . getName ( ) + "'. Has to be a subclass of '" + expectedBaseType . getName ( ) + "'" ) ; } }


Input: Return the imports to use if the { [CODESPLIT] private String [ ] getProxyImports ( ) { List < String > result = new ArrayList <> ( ) ; result . add ( AutoProxyRegistrar . class . getName ( ) ) ; result . add ( ReactiveMethodSecurityConfiguration . class . getName ( ) ) ; return result . toArray ( new String [ result . size ( ) ] ) ; }


Input: Register the default AccessDecisionManager . Adds the special JSR 250 voter jsr - 250 is enabled and an expression voter if expression - based access control is enabled . [CODESPLIT] @ SuppressWarnings ( { "unchecked" , "rawtypes" } ) private String registerAccessManager ( ParserContext pc , boolean jsr250Enabled , BeanDefinition expressionVoter ) { BeanDefinitionBuilder accessMgrBuilder = BeanDefinitionBuilder . rootBeanDefinition ( AffirmativeBased . class ) ; ManagedList voters = new ManagedList ( 4 ) ; if ( expressionVoter != null ) { voters . add ( expressionVoter ) ; } voters . add ( new RootBeanDefinition ( RoleVoter . class ) ) ; voters . add ( new RootBeanDefinition ( AuthenticatedVoter . class ) ) ; if ( jsr250Enabled ) { voters . add ( new RootBeanDefinition ( Jsr250Voter . class ) ) ; } accessMgrBuilder . addConstructorArgValue ( voters ) ; BeanDefinition accessManager = accessMgrBuilder . getBeanDefinition ( ) ; String id = pc . getReaderContext ( ) . generateBeanName ( accessManager ) ; pc . registerBeanComponent ( new BeanComponentDefinition ( accessManager , id ) ) ; return id ; }


Input: Set the policy directive ( s ) to be used in the response header . [CODESPLIT] public void setPolicyDirectives ( String policyDirectives ) { Assert . hasLength ( policyDirectives , "policyDirectives must not be null or empty" ) ; this . policyDirectives = policyDirectives ; this . delegate = createDelegate ( ) ; }


Input: Sets the { @link Converter } used for converting the { @link OAuth2AuthorizationCodeGrantRequest } to a { @link RequestEntity } representation of the OAuth 2 . 0 Access Token Request . [CODESPLIT] public void setRequestEntityConverter ( Converter < OAuth2AuthorizationCodeGrantRequest , RequestEntity < ? > > requestEntityConverter ) { Assert . notNull ( requestEntityConverter , "requestEntityConverter cannot be null" ) ; this . requestEntityConverter = requestEntityConverter ; }


Input: Sets additional exception to event mappings . These are automatically merged with the default exception to event mappings that <code > ProviderManager< / code > defines . [CODESPLIT] @ SuppressWarnings ( { "unchecked" } ) public void setAdditionalExceptionMappings ( Properties additionalExceptionMappings ) { Assert . notNull ( additionalExceptionMappings , "The exceptionMappings object must not be null" ) ; for ( Object exceptionClass : additionalExceptionMappings . keySet ( ) ) { String eventClass = ( String ) additionalExceptionMappings . get ( exceptionClass ) ; try { Class < ? > clazz = getClass ( ) . getClassLoader ( ) . loadClass ( eventClass ) ; Assert . isAssignable ( AbstractAuthenticationFailureEvent . class , clazz ) ; addMapping ( ( String ) exceptionClass , ( Class < ? extends AbstractAuthenticationFailureEvent > ) clazz ) ; } catch ( ClassNotFoundException e ) { throw new RuntimeException ( "Failed to load authentication event class " + eventClass ) ; } } }


Input: Modifies the { @link ClientRequest#attributes () } to include the { @link OAuth2AuthorizedClient } to be used for providing the Bearer Token . Example usage : [CODESPLIT] public static Consumer < Map < String , Object > > serverWebExchange ( ServerWebExchange serverWebExchange ) { return attributes -> attributes . put ( SERVER_WEB_EXCHANGE_ATTR_NAME , serverWebExchange ) ; }


Input: Handles the HttpSessionEvent by publishing a { @link HttpSessionCreatedEvent } to the application appContext . [CODESPLIT] public void sessionCreated ( HttpSessionEvent event ) { HttpSessionCreatedEvent e = new HttpSessionCreatedEvent ( event . getSession ( ) ) ; Log log = LogFactory . getLog ( LOGGER_NAME ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Publishing event: " + e ) ; } getContext ( event . getSession ( ) . getServletContext ( ) ) . publishEvent ( e ) ; }


Input: Handles the HttpSessionEvent by publishing a { @link HttpSessionDestroyedEvent } to the application appContext . [CODESPLIT] public void sessionDestroyed ( HttpSessionEvent event ) { HttpSessionDestroyedEvent e = new HttpSessionDestroyedEvent ( event . getSession ( ) ) ; Log log = LogFactory . getLog ( LOGGER_NAME ) ; if ( log . isDebugEnabled ( ) ) { log . debug ( "Publishing event: " + e ) ; } getContext ( event . getSession ( ) . getServletContext ( ) ) . publishEvent ( e ) ; }


Input: Converts an array of GrantedAuthority objects to a Set . [CODESPLIT] public static Set < String > authorityListToSet ( Collection < ? extends GrantedAuthority > userAuthorities ) { Assert . notNull ( userAuthorities , "userAuthorities cannot be null" ) ; Set < String > set = new HashSet <> ( userAuthorities . size ( ) ) ; for ( GrantedAuthority authority : userAuthorities ) { set . add ( authority . getAuthority ( ) ) ; } return set ; }


Input: Constant time comparison to prevent against timing attacks . [CODESPLIT] private boolean matches ( byte [ ] expected , byte [ ] actual ) { if ( expected . length != actual . length ) { return false ; } int result = 0 ; for ( int i = 0 ; i < expected . length ; i ++ ) { result |= expected [ i ] ^ actual [ i ] ; } return result == 0 ; }


Input: Returns the { @link RequestEntity } used for the Access Token Request . [CODESPLIT] @ Override public RequestEntity < ? > convert ( OAuth2AuthorizationCodeGrantRequest authorizationCodeGrantRequest ) { ClientRegistration clientRegistration = authorizationCodeGrantRequest . getClientRegistration ( ) ; HttpHeaders headers = OAuth2AuthorizationGrantRequestEntityUtils . getTokenRequestHeaders ( clientRegistration ) ; MultiValueMap < String , String > formParameters = this . buildFormParameters ( authorizationCodeGrantRequest ) ; URI uri = UriComponentsBuilder . fromUriString ( clientRegistration . getProviderDetails ( ) . getTokenUri ( ) ) . build ( ) . toUri ( ) ; return new RequestEntity <> ( formParameters , headers , HttpMethod . POST , uri ) ; }


Input: Returns a { @link MultiValueMap } of the form parameters used for the Access Token Request body . [CODESPLIT] private MultiValueMap < String , String > buildFormParameters ( OAuth2AuthorizationCodeGrantRequest authorizationCodeGrantRequest ) { ClientRegistration clientRegistration = authorizationCodeGrantRequest . getClientRegistration ( ) ; OAuth2AuthorizationExchange authorizationExchange = authorizationCodeGrantRequest . getAuthorizationExchange ( ) ; MultiValueMap < String , String > formParameters = new LinkedMultiValueMap <> ( ) ; formParameters . add ( OAuth2ParameterNames . GRANT_TYPE , authorizationCodeGrantRequest . getGrantType ( ) . getValue ( ) ) ; formParameters . add ( OAuth2ParameterNames . CODE , authorizationExchange . getAuthorizationResponse ( ) . getCode ( ) ) ; String redirectUri = authorizationExchange . getAuthorizationRequest ( ) . getRedirectUri ( ) ; String codeVerifier = authorizationExchange . getAuthorizationRequest ( ) . getAttribute ( PkceParameterNames . CODE_VERIFIER ) ; if ( redirectUri != null ) { formParameters . add ( OAuth2ParameterNames . REDIRECT_URI , redirectUri ) ; } if ( ! ClientAuthenticationMethod . BASIC . equals ( clientRegistration . getClientAuthenticationMethod ( ) ) ) { formParameters . add ( OAuth2ParameterNames . CLIENT_ID , clientRegistration . getClientId ( ) ) ; } if ( ClientAuthenticationMethod . POST . equals ( clientRegistration . getClientAuthenticationMethod ( ) ) ) { formParameters . add ( OAuth2ParameterNames . CLIENT_SECRET , clientRegistration . getClientSecret ( ) ) ; } if ( codeVerifier != null ) { formParameters . add ( PkceParameterNames . CODE_VERIFIER , codeVerifier ) ; } return formParameters ; }


Input: Sets the base { @code URI } used for authorization requests . [CODESPLIT] public ImplicitGrantConfigurer < B > authorizationRequestBaseUri ( String authorizationRequestBaseUri ) { Assert . hasText ( authorizationRequestBaseUri , "authorizationRequestBaseUri cannot be empty" ) ; this . authorizationRequestBaseUri = authorizationRequestBaseUri ; return this ; }


Input: Sets the repository of client registrations . [CODESPLIT] public ImplicitGrantConfigurer < B > clientRegistrationRepository ( ClientRegistrationRepository clientRegistrationRepository ) { Assert . notNull ( clientRegistrationRepository , "clientRegistrationRepository cannot be null" ) ; this . getBuilder ( ) . setSharedObject ( ClientRegistrationRepository . class , clientRegistrationRepository ) ; return this ; }


Input: Performs the redirect or forward to the { [CODESPLIT] public void onAuthenticationFailure ( HttpServletRequest request , HttpServletResponse response , AuthenticationException exception ) throws IOException , ServletException { if ( defaultFailureUrl == null ) { logger . debug ( "No failure URL set, sending 401 Unauthorized error" ) ; response . sendError ( HttpStatus . UNAUTHORIZED . value ( ) , HttpStatus . UNAUTHORIZED . getReasonPhrase ( ) ) ; } else { saveException ( request , exception ) ; if ( forwardToDestination ) { logger . debug ( "Forwarding to " + defaultFailureUrl ) ; request . getRequestDispatcher ( defaultFailureUrl ) . forward ( request , response ) ; } else { logger . debug ( "Redirecting to " + defaultFailureUrl ) ; redirectStrategy . sendRedirect ( request , response , defaultFailureUrl ) ; } } }


Input: Caches the { [CODESPLIT] protected final void saveException ( HttpServletRequest request , AuthenticationException exception ) { if ( forwardToDestination ) { request . setAttribute ( WebAttributes . AUTHENTICATION_EXCEPTION , exception ) ; } else { HttpSession session = request . getSession ( false ) ; if ( session != null || allowSessionCreation ) { request . getSession ( ) . setAttribute ( WebAttributes . AUTHENTICATION_EXCEPTION , exception ) ; } } }


Input: The URL which will be used as the failure destination . [CODESPLIT] public void setDefaultFailureUrl ( String defaultFailureUrl ) { Assert . isTrue ( UrlUtils . isValidRedirectUrl ( defaultFailureUrl ) , ( ) -> "'" + defaultFailureUrl + "' is not a valid redirect URL" ) ; this . defaultFailureUrl = defaultFailureUrl ; }


Input: Authenticate the given PreAuthenticatedAuthenticationToken . <p > If the principal contained in the authentication object is null the request will be ignored to allow other providers to authenticate it . [CODESPLIT] public Authentication authenticate ( Authentication authentication ) throws AuthenticationException { if ( ! supports ( authentication . getClass ( ) ) ) { return null ; } if ( logger . isDebugEnabled ( ) ) { logger . debug ( "PreAuthenticated authentication request: " + authentication ) ; } if ( authentication . getPrincipal ( ) == null ) { logger . debug ( "No pre-authenticated principal found in request." ) ; if ( throwExceptionWhenTokenRejected ) { throw new BadCredentialsException ( "No pre-authenticated principal found in request." ) ; } return null ; } if ( authentication . getCredentials ( ) == null ) { logger . debug ( "No pre-authenticated credentials found in request." ) ; if ( throwExceptionWhenTokenRejected ) { throw new BadCredentialsException ( "No pre-authenticated credentials found in request." ) ; } return null ; } UserDetails ud = preAuthenticatedUserDetailsService . loadUserDetails ( ( PreAuthenticatedAuthenticationToken ) authentication ) ; userDetailsChecker . check ( ud ) ; PreAuthenticatedAuthenticationToken result = new PreAuthenticatedAuthenticationToken ( ud , authentication . getCredentials ( ) , ud . getAuthorities ( ) ) ; result . setDetails ( authentication . getDetails ( ) ) ; return result ; }


Input: Sets a Function used to resolve a Map of the hidden inputs where the key is the name of the input and the value is the value of the input . Typically this is used to resolve the CSRF token . [CODESPLIT] public void setResolveHiddenInputs ( Function < HttpServletRequest , Map < String , String > > resolveHiddenInputs ) { Assert . notNull ( resolveHiddenInputs , "resolveHiddenInputs cannot be null" ) ; this . resolveHiddenInputs = resolveHiddenInputs ; }


Input: Introspect and validate the opaque <a href = https : // tools . ietf . org / html / rfc6750#section - 1 . 2 target = _blank > Bearer Token< / a > . [CODESPLIT] @ Override public Authentication authenticate ( Authentication authentication ) throws AuthenticationException { if ( ! ( authentication instanceof BearerTokenAuthenticationToken ) ) { return null ; } BearerTokenAuthenticationToken bearer = ( BearerTokenAuthenticationToken ) authentication ; Map < String , Object > claims ; try { claims = this . introspectionClient . introspect ( bearer . getToken ( ) ) ; } catch ( OAuth2IntrospectionException failed ) { OAuth2Error invalidToken = invalidToken ( failed . getMessage ( ) ) ; throw new OAuth2AuthenticationException ( invalidToken ) ; } AbstractAuthenticationToken result = convert ( bearer . getToken ( ) , claims ) ; result . setDetails ( bearer . getDetails ( ) ) ; return result ; }


Input: Get a UserDetails object based on the user name contained in the given token and the GrantedAuthorities as returned by the GrantedAuthoritiesContainer implementation as returned by the token . getDetails () method . [CODESPLIT] public final UserDetails loadUserDetails ( PreAuthenticatedAuthenticationToken token ) throws AuthenticationException { Assert . notNull ( token . getDetails ( ) , "token.getDetails() cannot be null" ) ; Assert . isInstanceOf ( GrantedAuthoritiesContainer . class , token . getDetails ( ) ) ; Collection < ? extends GrantedAuthority > authorities = ( ( GrantedAuthoritiesContainer ) token . getDetails ( ) ) . getGrantedAuthorities ( ) ; return createUserDetails ( token , authorities ) ; }


Input: Creates the final <tt > UserDetails< / tt > object . Can be overridden to customize the contents . [CODESPLIT] protected UserDetails createUserDetails ( Authentication token , Collection < ? extends GrantedAuthority > authorities ) { return new User ( token . getName ( ) , "N/A" , true , true , true , true , authorities ) ; }


Input: Construct a failure { @link OAuth2TokenValidatorResult } with the provided detail [CODESPLIT] public static OAuth2TokenValidatorResult failure ( Collection < OAuth2Error > errors ) { if ( errors . isEmpty ( ) ) { return NO_ERRORS ; } return new OAuth2TokenValidatorResult ( errors ) ; }


Input: Gets the { @link RequestCache } to use . If one is defined using { @link #requestCache ( org . springframework . security . web . savedrequest . RequestCache ) } then it is used . Otherwise an attempt to find a { @link RequestCache } shared object is made . If that fails an { @link HttpSessionRequestCache } is used [CODESPLIT] private RequestCache getRequestCache ( H http ) { RequestCache result = http . getSharedObject ( RequestCache . class ) ; if ( result != null ) { return result ; } result = getBeanOrNull ( RequestCache . class ) ; if ( result != null ) { return result ; } HttpSessionRequestCache defaultCache = new HttpSessionRequestCache ( ) ; defaultCache . setRequestMatcher ( createDefaultSavedRequestMatcher ( http ) ) ; return defaultCache ; }


Input: ======================================================================================================== [CODESPLIT] public static String buildFullRequestUrl ( HttpServletRequest r ) { return buildFullRequestUrl ( r . getScheme ( ) , r . getServerName ( ) , r . getServerPort ( ) , r . getRequestURI ( ) , r . getQueryString ( ) ) ; }


Input: Obtains the full URL the client used to make the request . <p > Note that the server port will not be shown if it is the default server port for HTTP or HTTPS ( 80 and 443 respectively ) . [CODESPLIT] public static String buildFullRequestUrl ( String scheme , String serverName , int serverPort , String requestURI , String queryString ) { scheme = scheme . toLowerCase ( ) ; StringBuilder url = new StringBuilder ( ) ; url . append ( scheme ) . append ( "://" ) . append ( serverName ) ; // Only add port if not default if ( "http" . equals ( scheme ) ) { if ( serverPort != 80 ) { url . append ( ":" ) . append ( serverPort ) ; } } else if ( "https" . equals ( scheme ) ) { if ( serverPort != 443 ) { url . append ( ":" ) . append ( serverPort ) ; } } // Use the requestURI as it is encoded (RFC 3986) and hence suitable for // redirects. url . append ( requestURI ) ; if ( queryString != null ) { url . append ( "?" ) . append ( queryString ) ; } return url . toString ( ) ; }


Input: Obtains the web application - specific fragment of the request URL . <p > Under normal spec conditions [CODESPLIT] public static String buildRequestUrl ( HttpServletRequest r ) { return buildRequestUrl ( r . getServletPath ( ) , r . getRequestURI ( ) , r . getContextPath ( ) , r . getPathInfo ( ) , r . getQueryString ( ) ) ; }


Input: Obtains the web application - specific fragment of the URL . [CODESPLIT] private static String buildRequestUrl ( String servletPath , String requestURI , String contextPath , String pathInfo , String queryString ) { StringBuilder url = new StringBuilder ( ) ; if ( servletPath != null ) { url . append ( servletPath ) ; if ( pathInfo != null ) { url . append ( pathInfo ) ; } } else { url . append ( requestURI . substring ( contextPath . length ( ) ) ) ; } if ( queryString != null ) { url . append ( "?" ) . append ( queryString ) ; } return url . toString ( ) ; }


Input: Decides if a URL is absolute based on whether it contains a valid scheme name as defined in RFC 1738 . [CODESPLIT] public static boolean isAbsoluteUrl ( String url ) { if ( url == null ) { return false ; } final Pattern ABSOLUTE_URL = Pattern . compile ( "\\A[a-z0-9.+-]+://.*" , Pattern . CASE_INSENSITIVE ) ; return ABSOLUTE_URL . matcher ( url ) . matches ( ) ; }


Input: Iterates through the patterns stored in the map and returns the list of attributes defined for the first match . If no match is found returns an empty list . [CODESPLIT] public List < OpenIDAttribute > createAttributeList ( String identifier ) { for ( Map . Entry < Pattern , List < OpenIDAttribute > > entry : idToAttributes . entrySet ( ) ) { if ( entry . getKey ( ) . matcher ( identifier ) . matches ( ) ) { return entry . getValue ( ) ; } } return Collections . emptyList ( ) ; }


Input: ======================================================================================================== [CODESPLIT] @ Override public void afterPropertiesSet ( ) { Assert . hasLength ( key , "key must have length" ) ; Assert . notNull ( principal , "Anonymous authentication principal must be set" ) ; Assert . notNull ( authorities , "Anonymous authorities must be set" ) ; }


Input: Returns a representation of the active bits in the presented mask with each active bit being denoted by the passed character . <p > Inactive bits will be denoted by character { @link Permission#RESERVED_OFF } . [CODESPLIT] public static String printBinary ( int mask , char code ) { Assert . doesNotContain ( Character . toString ( code ) , Character . toString ( Permission . RESERVED_ON ) , ( ) -> Permission . RESERVED_ON + " is a reserved character code" ) ; Assert . doesNotContain ( Character . toString ( code ) , Character . toString ( Permission . RESERVED_OFF ) , ( ) -> Permission . RESERVED_OFF + " is a reserved character code" ) ; return printBinary ( mask , Permission . RESERVED_ON , Permission . RESERVED_OFF ) . replace ( Permission . RESERVED_ON , code ) ; }


Input: Converts the raw type from the database into the right Java type . For most applications the raw type will be Long for some applications it could be String . [CODESPLIT] Serializable identifierFrom ( Serializable identifier , ResultSet resultSet ) throws SQLException { if ( isString ( identifier ) && hasValidClassIdType ( resultSet ) && canConvertFromStringTo ( classIdTypeFrom ( resultSet ) ) ) { identifier = convertFromStringTo ( ( String ) identifier , classIdTypeFrom ( resultSet ) ) ; } else { // Assume it should be a Long type identifier = convertToLong ( identifier ) ; } return identifier ; }


Input: Converts to a { [CODESPLIT] private Long convertToLong ( Serializable identifier ) { Long idAsLong ; if ( canConvertFromStringTo ( Long . class ) ) { idAsLong = conversionService . convert ( identifier , Long . class ) ; } else { idAsLong = Long . valueOf ( identifier . toString ( ) ) ; } return idAsLong ; }


Input: <p > <b > WARNING : < / b > This method is considered unsafe for production and is only intended for sample applications . < / p > <p > Creates a user and automatically encodes the provided password using { @code PasswordEncoderFactories . createDelegatingPasswordEncoder () } . For example : < / p > [CODESPLIT] @ Deprecated public static UserBuilder withDefaultPasswordEncoder ( ) { logger . warn ( "User.withDefaultPasswordEncoder() is considered unsafe for production and is only intended for sample applications." ) ; PasswordEncoder encoder = PasswordEncoderFactories . createDelegatingPasswordEncoder ( ) ; return builder ( ) . passwordEncoder ( encoder :: encode ) ; }


Input: Creates a { @link ClientRegistration . Builder } using the provided  Issuer by making an  OpenID Provider Configuration Request and using the values in the  OpenID Provider Configuration Response to initialize the { @link ClientRegistration . Builder } . [CODESPLIT] public static ClientRegistration . Builder fromOidcIssuerLocation ( String issuer ) { String openidConfiguration = getOpenidConfiguration ( issuer ) ; OIDCProviderMetadata metadata = parse ( openidConfiguration ) ; String metadataIssuer = metadata . getIssuer ( ) . getValue ( ) ; if ( ! issuer . equals ( metadataIssuer ) ) { throw new IllegalStateException ( "The Issuer \"" + metadataIssuer + "\" provided in the OpenID Configuration did not match the requested issuer \"" + issuer + "\"" ) ; } String name = URI . create ( issuer ) . getHost ( ) ; ClientAuthenticationMethod method = getClientAuthenticationMethod ( issuer , metadata . getTokenEndpointAuthMethods ( ) ) ; List < GrantType > grantTypes = metadata . getGrantTypes ( ) ; // If null, the default includes authorization_code if ( grantTypes != null && ! grantTypes . contains ( GrantType . AUTHORIZATION_CODE ) ) { throw new IllegalArgumentException ( "Only AuthorizationGrantType.AUTHORIZATION_CODE is supported. The issuer \"" + issuer + "\" returned a configuration of " + grantTypes ) ; } List < String > scopes = getScopes ( metadata ) ; Map < String , Object > configurationMetadata = new LinkedHashMap <> ( metadata . toJSONObject ( ) ) ; return ClientRegistration . withRegistrationId ( name ) . userNameAttributeName ( IdTokenClaimNames . SUB ) . scope ( scopes ) . authorizationGrantType ( AuthorizationGrantType . AUTHORIZATION_CODE ) . clientAuthenticationMethod ( method ) . redirectUriTemplate ( "{baseUrl}/{action}/oauth2/code/{registrationId}" ) . authorizationUri ( metadata . getAuthorizationEndpointURI ( ) . toASCIIString ( ) ) . jwkSetUri ( metadata . getJWKSetURI ( ) . toASCIIString ( ) ) . providerConfigurationMetadata ( configurationMetadata ) . userInfoUri ( metadata . getUserInfoEndpointURI ( ) . toASCIIString ( ) ) . tokenUri ( metadata . getTokenEndpointURI ( ) . toASCIIString ( ) ) . clientName ( issuer ) ; }


Input: ======================================================================================================== [CODESPLIT] public Authentication buildRunAs ( Authentication authentication , Object object , Collection < ConfigAttribute > config ) { return null ; }


Input: Clears the { @link CsrfToken } [CODESPLIT] @ Override public Mono < Void > logout ( WebFilterExchange exchange , Authentication authentication ) { return this . csrfTokenRepository . saveToken ( exchange . getExchange ( ) , null ) ; }


Input: Shortcut to specify the { @link AccessDeniedHandler } to be used is a specific error page [CODESPLIT] public ExceptionHandlingConfigurer < H > accessDeniedPage ( String accessDeniedUrl ) { AccessDeniedHandlerImpl accessDeniedHandler = new AccessDeniedHandlerImpl ( ) ; accessDeniedHandler . setErrorPage ( accessDeniedUrl ) ; return accessDeniedHandler ( accessDeniedHandler ) ; }


Input: Sets a default { @link AccessDeniedHandler } to be used which prefers being invoked for the provided { @link RequestMatcher } . If only a single default { @link AccessDeniedHandler } is specified it will be what is used for the default { @link AccessDeniedHandler } . If multiple default { @link AccessDeniedHandler } instances are configured then a { @link RequestMatcherDelegatingAccessDeniedHandler } will be used . [CODESPLIT] public ExceptionHandlingConfigurer < H > defaultAccessDeniedHandlerFor ( AccessDeniedHandler deniedHandler , RequestMatcher preferredMatcher ) { this . defaultDeniedHandlerMappings . put ( preferredMatcher , deniedHandler ) ; return this ; }


Input: Sets a default { @link AuthenticationEntryPoint } to be used which prefers being invoked for the provided { @link RequestMatcher } . If only a single default { @link AuthenticationEntryPoint } is specified it will be what is used for the default { @link AuthenticationEntryPoint } . If multiple default { @link AuthenticationEntryPoint } instances are configured then a { @link DelegatingAuthenticationEntryPoint } will be used . [CODESPLIT] public ExceptionHandlingConfigurer < H > defaultAuthenticationEntryPointFor ( AuthenticationEntryPoint entryPoint , RequestMatcher preferredMatcher ) { this . defaultEntryPointMappings . put ( preferredMatcher , entryPoint ) ; return this ; }


Input: Gets the { [CODESPLIT] AccessDeniedHandler getAccessDeniedHandler ( H http ) { AccessDeniedHandler deniedHandler = this . accessDeniedHandler ; if ( deniedHandler == null ) { deniedHandler = createDefaultDeniedHandler ( http ) ; } return deniedHandler ; }


Input: Gets the { [CODESPLIT] AuthenticationEntryPoint getAuthenticationEntryPoint ( H http ) { AuthenticationEntryPoint entryPoint = this . authenticationEntryPoint ; if ( entryPoint == null ) { entryPoint = createDefaultEntryPoint ( http ) ; } return entryPoint ; }


Input: Gets the { @link RequestCache } to use . If one is defined using { @link #requestCache ( org . springframework . security . web . savedrequest . RequestCache ) } then it is used . Otherwise an attempt to find a { @link RequestCache } shared object is made . If that fails an { @link HttpSessionRequestCache } is used [CODESPLIT] private RequestCache getRequestCache ( H http ) { RequestCache result = http . getSharedObject ( RequestCache . class ) ; if ( result != null ) { return result ; } return new HttpSessionRequestCache ( ) ; }


Input: Converts the supplied { @link Map } of role name to implied role name ( s ) to a string representation understood by { @link RoleHierarchyImpl#setHierarchy ( String ) } . The map key is the role name and the map value is a { @link List } of implied role name ( s ) . [CODESPLIT] public static String roleHierarchyFromMap ( Map < String , List < String > > roleHierarchyMap ) { Assert . notEmpty ( roleHierarchyMap , "roleHierarchyMap cannot be empty" ) ; StringWriter roleHierarchyBuffer = new StringWriter ( ) ; PrintWriter roleHierarchyWriter = new PrintWriter ( roleHierarchyBuffer ) ; for ( Map . Entry < String , List < String > > roleHierarchyEntry : roleHierarchyMap . entrySet ( ) ) { String role = roleHierarchyEntry . getKey ( ) ; List < String > impliedRoles = roleHierarchyEntry . getValue ( ) ; Assert . hasLength ( role , "role name must be supplied" ) ; Assert . notEmpty ( impliedRoles , "implied role name(s) cannot be empty" ) ; for ( String impliedRole : impliedRoles ) { String roleMapping = role + " > " + impliedRole ; roleHierarchyWriter . println ( roleMapping ) ; } } return roleHierarchyBuffer . toString ( ) ; }


Input: ======================================================================================================== [CODESPLIT] public MutableAcl createAcl ( ObjectIdentity objectIdentity ) throws AlreadyExistsException { Assert . notNull ( objectIdentity , "Object Identity required" ) ; // Check this object identity hasn't already been persisted if ( retrieveObjectIdentityPrimaryKey ( objectIdentity ) != null ) { throw new AlreadyExistsException ( "Object identity '" + objectIdentity + "' already exists" ) ; } // Need to retrieve the current principal, in order to know who "owns" this ACL // (can be changed later on) Authentication auth = SecurityContextHolder . getContext ( ) . getAuthentication ( ) ; PrincipalSid sid = new PrincipalSid ( auth ) ; // Create the acl_object_identity row createObjectIdentity ( objectIdentity , sid ) ; // Retrieve the ACL via superclass (ensures cache registration, proper retrieval // etc) Acl acl = readAclById ( objectIdentity ) ; Assert . isInstanceOf ( MutableAcl . class , acl , "MutableAcl should be been returned" ) ; return ( MutableAcl ) acl ; }


Input: Creates a new row in acl_entry for every ACE defined in the passed MutableAcl object . [CODESPLIT] protected void createEntries ( final MutableAcl acl ) { if ( acl . getEntries ( ) . isEmpty ( ) ) { return ; } jdbcOperations . batchUpdate ( insertEntry , new BatchPreparedStatementSetter ( ) { public int getBatchSize ( ) { return acl . getEntries ( ) . size ( ) ; } public void setValues ( PreparedStatement stmt , int i ) throws SQLException { AccessControlEntry entry_ = acl . getEntries ( ) . get ( i ) ; Assert . isTrue ( entry_ instanceof AccessControlEntryImpl , "Unknown ACE class" ) ; AccessControlEntryImpl entry = ( AccessControlEntryImpl ) entry_ ; stmt . setLong ( 1 , ( ( Long ) acl . getId ( ) ) . longValue ( ) ) ; stmt . setInt ( 2 , i ) ; stmt . setLong ( 3 , createOrRetrieveSidPrimaryKey ( entry . getSid ( ) , true ) . longValue ( ) ) ; stmt . setInt ( 4 , entry . getPermission ( ) . getMask ( ) ) ; stmt . setBoolean ( 5 , entry . isGranting ( ) ) ; stmt . setBoolean ( 6 , entry . isAuditSuccess ( ) ) ; stmt . setBoolean ( 7 , entry . isAuditFailure ( ) ) ; } } ) ; }


Input: Creates an entry in the acl_object_identity table for the passed ObjectIdentity . The Sid is also necessary as acl_object_identity has defined the sid column as non - null . [CODESPLIT] protected void createObjectIdentity ( ObjectIdentity object , Sid owner ) { Long sidId = createOrRetrieveSidPrimaryKey ( owner , true ) ; Long classId = createOrRetrieveClassPrimaryKey ( object . getType ( ) , true , object . getIdentifier ( ) . getClass ( ) ) ; jdbcOperations . update ( insertObjectIdentity , classId , object . getIdentifier ( ) . toString ( ) , sidId , Boolean . TRUE ) ; }


Input: Retrieves the primary key from { @code acl_class } creating a new row if needed and the { @code allowCreate } property is { @code true } . [CODESPLIT] protected Long createOrRetrieveClassPrimaryKey ( String type , boolean allowCreate , Class idType ) { List < Long > classIds = jdbcOperations . queryForList ( selectClassPrimaryKey , new Object [ ] { type } , Long . class ) ; if ( ! classIds . isEmpty ( ) ) { return classIds . get ( 0 ) ; } if ( allowCreate ) { if ( ! isAclClassIdSupported ( ) ) { jdbcOperations . update ( insertClass , type ) ; } else { jdbcOperations . update ( insertClass , type , idType . getCanonicalName ( ) ) ; } Assert . isTrue ( TransactionSynchronizationManager . isSynchronizationActive ( ) , "Transaction must be running" ) ; return jdbcOperations . queryForObject ( classIdentityQuery , Long . class ) ; } return null ; }


Input: Retrieves the primary key from acl_sid creating a new row if needed and the allowCreate property is true . [CODESPLIT] protected Long createOrRetrieveSidPrimaryKey ( Sid sid , boolean allowCreate ) { Assert . notNull ( sid , "Sid required" ) ; String sidName ; boolean sidIsPrincipal = true ; if ( sid instanceof PrincipalSid ) { sidName = ( ( PrincipalSid ) sid ) . getPrincipal ( ) ; } else if ( sid instanceof GrantedAuthoritySid ) { sidName = ( ( GrantedAuthoritySid ) sid ) . getGrantedAuthority ( ) ; sidIsPrincipal = false ; } else { throw new IllegalArgumentException ( "Unsupported implementation of Sid" ) ; } return createOrRetrieveSidPrimaryKey ( sidName , sidIsPrincipal , allowCreate ) ; }


Input: Retrieves the primary key from acl_sid creating a new row if needed and the allowCreate property is true . [CODESPLIT] protected Long createOrRetrieveSidPrimaryKey ( String sidName , boolean sidIsPrincipal , boolean allowCreate ) { List < Long > sidIds = jdbcOperations . queryForList ( selectSidPrimaryKey , new Object [ ] { Boolean . valueOf ( sidIsPrincipal ) , sidName } , Long . class ) ; if ( ! sidIds . isEmpty ( ) ) { return sidIds . get ( 0 ) ; } if ( allowCreate ) { jdbcOperations . update ( insertSid , Boolean . valueOf ( sidIsPrincipal ) , sidName ) ; Assert . isTrue ( TransactionSynchronizationManager . isSynchronizationActive ( ) , "Transaction must be running" ) ; return jdbcOperations . queryForObject ( sidIdentityQuery , Long . class ) ; } return null ; }


Input: Retrieves the primary key from the acl_object_identity table for the passed ObjectIdentity . Unlike some other methods in this implementation this method will NOT create a row ( use { @link #createObjectIdentity ( ObjectIdentity Sid ) } instead ) . [CODESPLIT] protected Long retrieveObjectIdentityPrimaryKey ( ObjectIdentity oid ) { try { return jdbcOperations . queryForObject ( selectObjectIdentityPrimaryKey , Long . class , oid . getType ( ) , oid . getIdentifier ( ) . toString ( ) ) ; } catch ( DataAccessException notFound ) { return null ; } }


Input: This implementation will simply delete all ACEs in the database and recreate them on each invocation of this method . A more comprehensive implementation might use dirty state checking or more likely use ORM capabilities for create update and delete operations of { [CODESPLIT] public MutableAcl updateAcl ( MutableAcl acl ) throws NotFoundException { Assert . notNull ( acl . getId ( ) , "Object Identity doesn't provide an identifier" ) ; // Delete this ACL's ACEs in the acl_entry table deleteEntries ( retrieveObjectIdentityPrimaryKey ( acl . getObjectIdentity ( ) ) ) ; // Create this ACL's ACEs in the acl_entry table createEntries ( acl ) ; // Change the mutable columns in acl_object_identity updateObjectIdentity ( acl ) ; // Clear the cache, including children clearCacheIncludingChildren ( acl . getObjectIdentity ( ) ) ; // Retrieve the ACL via superclass (ensures cache registration, proper retrieval // etc) return ( MutableAcl ) super . readAclById ( acl . getObjectIdentity ( ) ) ; }


Input: Updates an existing acl_object_identity row with new information presented in the passed MutableAcl object . Also will create an acl_sid entry if needed for the Sid that owns the MutableAcl . [CODESPLIT] protected void updateObjectIdentity ( MutableAcl acl ) { Long parentId = null ; if ( acl . getParentAcl ( ) != null ) { Assert . isInstanceOf ( ObjectIdentityImpl . class , acl . getParentAcl ( ) . getObjectIdentity ( ) , "Implementation only supports ObjectIdentityImpl" ) ; ObjectIdentityImpl oii = ( ObjectIdentityImpl ) acl . getParentAcl ( ) . getObjectIdentity ( ) ; parentId = retrieveObjectIdentityPrimaryKey ( oii ) ; } Assert . notNull ( acl . getOwner ( ) , "Owner is required in this implementation" ) ; Long ownerSid = createOrRetrieveSidPrimaryKey ( acl . getOwner ( ) , true ) ; int count = jdbcOperations . update ( updateObjectIdentity , parentId , ownerSid , Boolean . valueOf ( acl . isEntriesInheriting ( ) ) , acl . getId ( ) ) ; if ( count != 1 ) { throw new NotFoundException ( "Unable to locate ACL to update" ) ; } }


Input: Stores the current request provided the configuration properties allow it . [CODESPLIT] public void saveRequest ( HttpServletRequest request , HttpServletResponse response ) { if ( requestMatcher . matches ( request ) ) { DefaultSavedRequest savedRequest = new DefaultSavedRequest ( request , portResolver ) ; if ( createSessionAllowed || request . getSession ( false ) != null ) { // Store the HTTP request itself. Used by // AbstractAuthenticationProcessingFilter // for redirection after successful authentication (SEC-29) request . getSession ( ) . setAttribute ( this . sessionAttrName , savedRequest ) ; logger . debug ( "DefaultSavedRequest added to Session: " + savedRequest ) ; } } else { logger . debug ( "Request not saved as configured RequestMatcher did not match" ) ; } }


Input: Creates a { @link DelegatingSecurityContextCallable } and with the given { @link Callable } and { @link SecurityContext } but if the securityContext is null will defaults to the current { @link SecurityContext } on the { @link SecurityContextHolder } [CODESPLIT] public static < V > Callable < V > create ( Callable < V > delegate , SecurityContext securityContext ) { return securityContext == null ? new DelegatingSecurityContextCallable <> ( delegate ) : new DelegatingSecurityContextCallable <> ( delegate , securityContext ) ; }


Input: <p > Sets the { @link LogoutHandler } s used when integrating with { @link HttpServletRequest } with Servlet 3 APIs . Specifically it will be used when { @link HttpServletRequest#logout () } is invoked in order to log the user out . So long as the { @link LogoutHandler } s do not commit the { @link HttpServletResponse } ( expected ) then the user is in charge of handling the response . < / p > <p > If the value is null ( default ) the default container behavior will be retained when invoking { @link HttpServletRequest#logout () } . < / p > [CODESPLIT] public void setLogoutHandlers ( List < LogoutHandler > logoutHandlers ) { this . logoutHandler = CollectionUtils . isEmpty ( logoutHandlers ) ? null : new CompositeLogoutHandler ( logoutHandlers ) ; }


Input: Creates a matcher that matches on the specific method and any of the provided patterns . [CODESPLIT] public static ServerWebExchangeMatcher pathMatchers ( HttpMethod method , String ... patterns ) { List < ServerWebExchangeMatcher > matchers = new ArrayList <> ( patterns . length ) ; for ( String pattern : patterns ) { matchers . add ( new PathPatternParserServerWebExchangeMatcher ( pattern , method ) ) ; } return new OrServerWebExchangeMatcher ( matchers ) ; }


Input: Matches any exchange [CODESPLIT] public static ServerWebExchangeMatcher anyExchange ( ) { // we don't use a lambda to ensure a unique equals and hashcode // which otherwise can cause problems with adding multiple entries to an ordered LinkedHashMap return new ServerWebExchangeMatcher ( ) { @ Override public Mono < MatchResult > matches ( ServerWebExchange exchange ) { return ServerWebExchangeMatcher . MatchResult . match ( ) ; } } ; }


Input: Creates a standard password - based bytes encryptor using 256 bit AES encryption with Galois Counter Mode ( GCM ) . Derives the secret key using PKCS #5 s PBKDF2 ( Password - Based Key Derivation Function #2 ) . Salts the password to prevent dictionary attacks against the key . The provided salt is expected to be hex - encoded ; it should be random and at least 8 bytes in length . Also applies a random 16 byte initialization vector to ensure each encrypted message will be unique . Requires Java 6 . [CODESPLIT] public static BytesEncryptor stronger ( CharSequence password , CharSequence salt ) { return new AesBytesEncryptor ( password . toString ( ) , salt , KeyGenerators . secureRandom ( 16 ) , CipherAlgorithm . GCM ) ; }


Input: Creates a standard password - based bytes encryptor using 256 bit AES encryption . Derives the secret key using PKCS #5 s PBKDF2 ( Password - Based Key Derivation Function #2 ) . Salts the password to prevent dictionary attacks against the key . The provided salt is expected to be hex - encoded ; it should be random and at least 8 bytes in length . Also applies a random 16 byte initialization vector to ensure each encrypted message will be unique . Requires Java 6 . [CODESPLIT] public static BytesEncryptor standard ( CharSequence password , CharSequence salt ) { return new AesBytesEncryptor ( password . toString ( ) , salt , KeyGenerators . secureRandom ( 16 ) ) ; }


Input: Creates a text encryptor that uses stronger password - based encryption . Encrypted text is hex - encoded . [CODESPLIT] public static TextEncryptor delux ( CharSequence password , CharSequence salt ) { return new HexEncodingTextEncryptor ( stronger ( password , salt ) ) ; }


Input: Creates a text encryptor that uses standard password - based encryption . Encrypted text is hex - encoded . [CODESPLIT] public static TextEncryptor text ( CharSequence password , CharSequence salt ) { return new HexEncodingTextEncryptor ( standard ( password , salt ) ) ; }


Input: Creates an encryptor for queryable text strings that uses standard password - based encryption . Uses a 16 - byte all - zero initialization vector so encrypting the same data results in the same encryption result . This is done to allow encrypted data to be queried against . Encrypted text is hex - encoded . [CODESPLIT] public static TextEncryptor queryableText ( CharSequence password , CharSequence salt ) { return new HexEncodingTextEncryptor ( new AesBytesEncryptor ( password . toString ( ) , salt ) ) ; }


Input: Set the { @link SecurityExpressionHandler } to be used . If this is null then a { @link DefaultWebSecurityExpressionHandler } will be used . [CODESPLIT] public WebSecurity expressionHandler ( SecurityExpressionHandler < FilterInvocation > expressionHandler ) { Assert . notNull ( expressionHandler , "expressionHandler cannot be null" ) ; this . expressionHandler = expressionHandler ; return this ; }


Input: Gets the { [CODESPLIT] public WebInvocationPrivilegeEvaluator getPrivilegeEvaluator ( ) { if ( privilegeEvaluator != null ) { return privilegeEvaluator ; } return filterSecurityInterceptor == null ? null : new DefaultWebInvocationPrivilegeEvaluator ( filterSecurityInterceptor ) ; }


Input: This concrete implementation polls all configured { @link AccessDecisionVoter } s for each { @link ConfigAttribute } and grants access if <b > only< / b > grant ( or abstain ) votes were received . <p > Other voting implementations usually pass the entire list of <tt > ConfigAttribute< / tt > s to the <code > AccessDecisionVoter< / code > . This implementation differs in that each <code > AccessDecisionVoter< / code > knows only about a single <code > ConfigAttribute< / code > at a time . <p > If every <code > AccessDecisionVoter< / code > abstained from voting the decision will be based on the { @link #isAllowIfAllAbstainDecisions () } property ( defaults to false ) . [CODESPLIT] public void decide ( Authentication authentication , Object object , Collection < ConfigAttribute > attributes ) throws AccessDeniedException { int grant = 0 ; List < ConfigAttribute > singleAttributeList = new ArrayList <> ( 1 ) ; singleAttributeList . add ( null ) ; for ( ConfigAttribute attribute : attributes ) { singleAttributeList . set ( 0 , attribute ) ; for ( AccessDecisionVoter voter : getDecisionVoters ( ) ) { int result = voter . vote ( authentication , object , singleAttributeList ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Voter: " + voter + ", returned: " + result ) ; } switch ( result ) { case AccessDecisionVoter . ACCESS_GRANTED : grant ++ ; break ; case AccessDecisionVoter . ACCESS_DENIED : throw new AccessDeniedException ( messages . getMessage ( "AbstractAccessDecisionManager.accessDenied" , "Access is denied" ) ) ; default : break ; } } } // To get this far, there were no deny votes if ( grant > 0 ) { return ; } // To get this far, every AccessDecisionVoter abstained checkAllowIfAllAbstainDecisions ( ) ; }


Input: Creates a { @link DelegatingPasswordEncoder } with default mappings . Additional mappings may be added and the encoding will be updated to conform with best practices . However due to the nature of { @link DelegatingPasswordEncoder } the updates should not impact users . The mappings current are : [CODESPLIT] @ SuppressWarnings ( "deprecation" ) public static PasswordEncoder createDelegatingPasswordEncoder ( ) { String encodingId = "bcrypt" ; Map < String , PasswordEncoder > encoders = new HashMap <> ( ) ; encoders . put ( encodingId , new BCryptPasswordEncoder ( ) ) ; encoders . put ( "ldap" , new org . springframework . security . crypto . password . LdapShaPasswordEncoder ( ) ) ; encoders . put ( "MD4" , new org . springframework . security . crypto . password . Md4PasswordEncoder ( ) ) ; encoders . put ( "MD5" , new org . springframework . security . crypto . password . MessageDigestPasswordEncoder ( "MD5" ) ) ; encoders . put ( "noop" , org . springframework . security . crypto . password . NoOpPasswordEncoder . getInstance ( ) ) ; encoders . put ( "pbkdf2" , new Pbkdf2PasswordEncoder ( ) ) ; encoders . put ( "scrypt" , new SCryptPasswordEncoder ( ) ) ; encoders . put ( "SHA-1" , new org . springframework . security . crypto . password . MessageDigestPasswordEncoder ( "SHA-1" ) ) ; encoders . put ( "SHA-256" , new org . springframework . security . crypto . password . MessageDigestPasswordEncoder ( "SHA-256" ) ) ; encoders . put ( "sha256" , new org . springframework . security . crypto . password . StandardPasswordEncoder ( ) ) ; return new DelegatingPasswordEncoder ( encodingId , encoders ) ; }


Input: Collect error details from the provided parameters and format according to RFC 6750 specifically { @code error } { @code error_description } { @code error_uri } and { @scope scope } . [CODESPLIT] @ Override public void handle ( HttpServletRequest request , HttpServletResponse response , AccessDeniedException accessDeniedException ) throws IOException , ServletException { Map < String , String > parameters = new LinkedHashMap <> ( ) ; if ( this . realmName != null ) { parameters . put ( "realm" , this . realmName ) ; } if ( request . getUserPrincipal ( ) instanceof AbstractOAuth2TokenAuthenticationToken ) { AbstractOAuth2TokenAuthenticationToken token = ( AbstractOAuth2TokenAuthenticationToken ) request . getUserPrincipal ( ) ; String scope = getScope ( token ) ; parameters . put ( "error" , BearerTokenErrorCodes . INSUFFICIENT_SCOPE ) ; parameters . put ( "error_description" , String . format ( "The token provided has insufficient scope [%s] for this request" , scope ) ) ; parameters . put ( "error_uri" , "https://tools.ietf.org/html/rfc6750#section-3.1" ) ; if ( StringUtils . hasText ( scope ) ) { parameters . put ( "scope" , scope ) ; } } String wwwAuthenticate = computeWWWAuthenticateHeaderValue ( parameters ) ; response . addHeader ( HttpHeaders . WWW_AUTHENTICATE , wwwAuthenticate ) ; response . setStatus ( HttpStatus . FORBIDDEN . value ( ) ) ; }


Input: Writes the X - Frame - Options header value overwritting any previous value . [CODESPLIT] public void writeHeaders ( HttpServletRequest request , HttpServletResponse response ) { if ( XFrameOptionsMode . ALLOW_FROM . equals ( frameOptionsMode ) ) { String allowFromValue = this . allowFromStrategy . getAllowFromValue ( request ) ; if ( XFrameOptionsMode . DENY . getMode ( ) . equals ( allowFromValue ) ) { if ( ! response . containsHeader ( XFRAME_OPTIONS_HEADER ) ) { response . setHeader ( XFRAME_OPTIONS_HEADER , XFrameOptionsMode . DENY . getMode ( ) ) ; } } else if ( allowFromValue != null ) { if ( ! response . containsHeader ( XFRAME_OPTIONS_HEADER ) ) { response . setHeader ( XFRAME_OPTIONS_HEADER , XFrameOptionsMode . ALLOW_FROM . getMode ( ) + " " + allowFromValue ) ; } } } else { response . setHeader ( XFRAME_OPTIONS_HEADER , frameOptionsMode . getMode ( ) ) ; } }


Input: <p > Attempts to obtain and run as a JAAS <code > Subject< / code > using { @link #obtainSubject ( ServletRequest ) } . < / p > [CODESPLIT] public final void doFilter ( final ServletRequest request , final ServletResponse response , final FilterChain chain ) throws ServletException , IOException { Subject subject = obtainSubject ( request ) ; if ( subject == null && createEmptySubject ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Subject returned was null and createEmtpySubject is true; creating new empty subject to run as." ) ; } subject = new Subject ( ) ; } if ( subject == null ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Subject is null continue running with no Subject." ) ; } chain . doFilter ( request , response ) ; return ; } final PrivilegedExceptionAction < Object > continueChain = new PrivilegedExceptionAction < Object > ( ) { public Object run ( ) throws IOException , ServletException { chain . doFilter ( request , response ) ; return null ; } } ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Running as Subject " + subject ) ; } try { Subject . doAs ( subject , continueChain ) ; } catch ( PrivilegedActionException e ) { throw new ServletException ( e . getMessage ( ) , e ) ; } }


Input: <p > Obtains the <code > Subject< / code > to run as or <code > null< / code > if no <code > Subject< / code > is available . < / p > <p > The default implementation attempts to obtain the <code > Subject< / code > from the <code > SecurityContext< / code > s <code > Authentication< / code > . If it is of type <code > JaasAuthenticationToken< / code > and is authenticated the <code > Subject< / code > is returned from it . Otherwise <code > null< / code > is returned . < / p > [CODESPLIT] protected Subject obtainSubject ( ServletRequest request ) { Authentication authentication = SecurityContextHolder . getContext ( ) . getAuthentication ( ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Attempting to obtainSubject using authentication : " + authentication ) ; } if ( authentication == null ) { return null ; } if ( ! authentication . isAuthenticated ( ) ) { return null ; } if ( ! ( authentication instanceof JaasAuthenticationToken ) ) { return null ; } JaasAuthenticationToken token = ( JaasAuthenticationToken ) authentication ; LoginContext loginContext = token . getLoginContext ( ) ; if ( loginContext == null ) { return null ; } return loginContext . getSubject ( ) ; }


Input: Specify the { @link CsrfTokenRepository } to use . The default is an { @link HttpSessionCsrfTokenRepository } wrapped by { @link LazyCsrfTokenRepository } . [CODESPLIT] public CsrfConfigurer < H > csrfTokenRepository ( CsrfTokenRepository csrfTokenRepository ) { Assert . notNull ( csrfTokenRepository , "csrfTokenRepository cannot be null" ) ; this . csrfTokenRepository = csrfTokenRepository ; return this ; }


Input: Specify the { @link RequestMatcher } to use for determining when CSRF should be applied . The default is to ignore GET HEAD TRACE OPTIONS and process all other requests . [CODESPLIT] public CsrfConfigurer < H > requireCsrfProtectionMatcher ( RequestMatcher requireCsrfProtectionMatcher ) { Assert . notNull ( requireCsrfProtectionMatcher , "requireCsrfProtectionMatcher cannot be null" ) ; this . requireCsrfProtectionMatcher = requireCsrfProtectionMatcher ; return this ; }


Input: <p > Allows specifying { @link HttpServletRequest } that should not use CSRF Protection even if they match the { @link #requireCsrfProtectionMatcher ( RequestMatcher ) } . < / p > [CODESPLIT] public CsrfConfigurer < H > ignoringAntMatchers ( String ... antPatterns ) { return new IgnoreCsrfProtectionRegistry ( this . context ) . antMatchers ( antPatterns ) . and ( ) ; }


Input: <p > Allows specifying { @link HttpServletRequest } s that should not use CSRF Protection even if they match the { @link #requireCsrfProtectionMatcher ( RequestMatcher ) } . < / p > [CODESPLIT] public CsrfConfigurer < H > ignoringRequestMatchers ( RequestMatcher ... requestMatchers ) { return new IgnoreCsrfProtectionRegistry ( this . context ) . requestMatchers ( requestMatchers ) . and ( ) ; }


Input: Gets the final { @link RequestMatcher } to use by combining the { @link #requireCsrfProtectionMatcher ( RequestMatcher ) } and any { @link #ignore () } . [CODESPLIT] private RequestMatcher getRequireCsrfProtectionMatcher ( ) { if ( this . ignoredCsrfProtectionMatchers . isEmpty ( ) ) { return this . requireCsrfProtectionMatcher ; } return new AndRequestMatcher ( this . requireCsrfProtectionMatcher , new NegatedRequestMatcher ( new OrRequestMatcher ( this . ignoredCsrfProtectionMatchers ) ) ) ; }