Input:
添加数词词元到结果集 [CODESPLIT] private void outputNumLexeme ( AnalyzeContext context ) { if ( nStart > - 1 && nEnd > - 1 ) { //输出数词
 Lexeme newLexeme = new Lexeme ( context . getBufferOffset ( ) , nStart , nEnd - nStart + 1 , Lexeme . TYPE_CNUM ) ; context . addLexeme ( newLexeme ) ; } }


Input: 匹配词段 [CODESPLIT] Hit match ( char [ ] charArray , int begin , int length ) { return this . match ( charArray , begin , length , null ) ; }


Input: 加载填充词典片段 [CODESPLIT] private synchronized void fillSegment ( char [ ] charArray , int begin , int length , int enabled ) { //获取字典表中的汉字对象 Character beginChar = Character . valueOf ( charArray [ begin ] ) ; Character keyChar = charMap . get ( beginChar ) ; //字典中没有该字，则将其添加入字典 if ( keyChar == null ) { charMap . put ( beginChar , beginChar ) ; keyChar = beginChar ; } //搜索当前节点的存储，查询对应keyChar的keyChar，如果没有则创建 DictSegment ds = lookforSegment ( keyChar , enabled ) ; if ( ds != null ) { //处理keyChar对应的segment if ( length > 1 ) { //词元还没有完全加入词典树 ds . fillSegment ( charArray , begin + 1 , length - 1 , enabled ) ; } else if ( length == 1 ) { //已经是词元的最后一个char,设置当前节点状态为enabled， //enabled=1表明一个完整的词，enabled=0表示从词典中屏蔽当前词 ds . nodeState = enabled ; } } }


Input: 查找本节点下对应的keyChar的segment * [CODESPLIT] private DictSegment lookforSegment ( Character keyChar , int create ) { DictSegment ds = null ; if ( this . storeSize <= ARRAY_LENGTH_LIMIT ) { //获取数组容器，如果数组未创建则创建数组 DictSegment [ ] segmentArray = getChildrenArray ( ) ; //搜寻数组 DictSegment keySegment = new DictSegment ( keyChar ) ; int position = Arrays . binarySearch ( segmentArray , 0 , this . storeSize , keySegment ) ; if ( position >= 0 ) { ds = segmentArray [ position ] ; } //遍历数组后没有找到对应的segment if ( ds == null && create == 1 ) { ds = keySegment ; if ( this . storeSize < ARRAY_LENGTH_LIMIT ) { //数组容量未满，使用数组存储 segmentArray [ this . storeSize ] = ds ; //segment数目+1 this . storeSize ++ ; Arrays . sort ( segmentArray , 0 , this . storeSize ) ; } else { //数组容量已满，切换Map存储 //获取Map容器，如果Map未创建,则创建Map Map < Character , DictSegment > segmentMap = getChildrenMap ( ) ; //将数组中的segment迁移到Map中 migrate ( segmentArray , segmentMap ) ; //存储新的segment segmentMap . put ( keyChar , ds ) ; //segment数目+1 ，  必须在释放数组前执行storeSize++ ， 确保极端情况下，不会取到空的数组 this . storeSize ++ ; //释放当前的数组引用 this . childrenArray = null ; } } } else { //获取Map容器，如果Map未创建,则创建Map Map < Character , DictSegment > segmentMap = getChildrenMap ( ) ; //搜索Map ds = ( DictSegment ) segmentMap . get ( keyChar ) ; if ( ds == null && create == 1 ) { //构造新的segment ds = new DictSegment ( keyChar ) ; segmentMap . put ( keyChar , ds ) ; //当前节点存储segment数目+1 this . storeSize ++ ; } } return ds ; }


Input: 获取Map容器 线程同步方法 [CODESPLIT] private Map < Character , DictSegment > getChildrenMap ( ) { synchronized ( this ) { if ( this . childrenMap == null ) { this . childrenMap = new ConcurrentHashMap < Character , DictSegment > ( ARRAY_LENGTH_LIMIT * 2 , 0.8f ) ; } } return this . childrenMap ; }


Input: 将数组中的segment迁移到Map中 [CODESPLIT] private void migrate ( DictSegment [ ] segmentArray , Map < Character , DictSegment > segmentMap ) { for ( DictSegment segment : segmentArray ) { if ( segment != null ) { segmentMap . put ( segment . nodeChar , segment ) ; } } }


Input:
/ * 词元在排序集合中的比较算法 [CODESPLIT] public int compareTo ( Lexeme other ) { //起始位置优先
 if ( this . begin < other . getBegin ( ) ) { return - 1 ; } else if ( this . begin == other . getBegin ( ) ) { //词元长度优先
 if ( this . length > other . getLength ( ) ) { return - 1 ; } else if ( this . length == other . getLength ( ) ) { return 0 ; } else { //this.length < other.getLength()
 return 1 ; } } else { //this.begin > other.getBegin()
 return 1 ; } }


Input: 获取词元类型标示字符串 [CODESPLIT] public String getLexemeTypeString ( ) { switch ( lexemeType ) { case TYPE_ENGLISH : return "ENGLISH" ; case TYPE_ARABIC : return "ARABIC" ; case TYPE_LETTER : return "LETTER" ; case TYPE_CNWORD : return "CN_WORD" ; case TYPE_CNCHAR : return "CN_CHAR" ; case TYPE_OTHER_CJK : return "OTHER_CJK" ; case TYPE_COUNT : return "COUNT" ; case TYPE_CNUM : return "TYPE_CNUM" ; case TYPE_CQUAN : return "TYPE_CQUAN" ; default : return "UNKONW" ; } }


Input: 合并两个相邻的词元 [CODESPLIT] public boolean append ( Lexeme l , int lexemeType ) { if ( l != null && this . getEndPosition ( ) == l . getBeginPosition ( ) ) { this . length += l . getLength ( ) ; this . lexemeType = lexemeType ; return true ; } else { return false ; } }


Input: Sets the { @link Converter } used for converting the OAuth 2 . 0 Error parameters to an { @link OAuth2Error } . [CODESPLIT] public final void setErrorConverter ( Converter < Map < String , String > , OAuth2Error > errorConverter ) { Assert . notNull ( errorConverter , "errorConverter cannot be null" ) ; this . errorConverter = errorConverter ; }


Input: Sets the { @link Converter } used for converting the { @link OAuth2Error } to a { @code Map } representation of the OAuth 2 . 0 Error parameters . [CODESPLIT] public final void setErrorParametersConverter ( Converter < OAuth2Error , Map < String , String > > errorParametersConverter ) { Assert . notNull ( errorParametersConverter , "errorParametersConverter cannot be null" ) ; this . errorParametersConverter = errorParametersConverter ; }


Input: Clears the { @link CsrfToken } [CODESPLIT] public void logout ( HttpServletRequest request , HttpServletResponse response , Authentication authentication ) { this . csrfTokenRepository . saveToken ( null , request , response ) ; }


Input: Sets the maximum acceptable clock skew . The default is 60 seconds . The clock skew is used when validating the { @link JwtClaimNames#EXP exp } and { @link JwtClaimNames#IAT iat } claims . [CODESPLIT] public final void setClockSkew ( Duration clockSkew ) { Assert . notNull ( clockSkew , "clockSkew cannot be null" ) ; Assert . isTrue ( clockSkew . getSeconds ( ) >= 0 , "clockSkew must be >= 0" ) ; this . clockSkew = clockSkew ; }


Input: Sets the { @link Converter Converter&lt ; Jwt Collection&lt ; GrantedAuthority&gt ; &gt ; } to use . Defaults to { @link JwtGrantedAuthoritiesConverter } . [CODESPLIT] public void setJwtGrantedAuthoritiesConverter ( Converter < Jwt , Collection < GrantedAuthority > > jwtGrantedAuthoritiesConverter ) { Assert . notNull ( jwtGrantedAuthoritiesConverter , "jwtGrantedAuthoritiesConverter cannot be null" ) ; this . jwtGrantedAuthoritiesConverter = jwtGrantedAuthoritiesConverter ; }


Input: Set to override the default HTTP port to HTTPS port mappings of 80 : 443 and 8080 : 8443 . In a Spring XML ApplicationContext a definition would look something like this : [CODESPLIT] public void setPortMappings ( Map < String , String > newMappings ) { Assert . notNull ( newMappings , "A valid list of HTTPS port mappings must be provided" ) ; this . httpsPortMappings . clear ( ) ; for ( Map . Entry < String , String > entry : newMappings . entrySet ( ) ) { Integer httpPort = Integer . valueOf ( entry . getKey ( ) ) ; Integer httpsPort = Integer . valueOf ( entry . getValue ( ) ) ; if ( ( httpPort . intValue ( ) < 1 ) || ( httpPort . intValue ( ) > 65535 ) || ( httpsPort . intValue ( ) < 1 ) || ( httpsPort . intValue ( ) > 65535 ) ) { throw new IllegalArgumentException ( "one or both ports out of legal range: " + httpPort + ", " + httpsPort ) ; } this . httpsPortMappings . put ( httpPort , httpsPort ) ; } if ( this . httpsPortMappings . size ( ) < 1 ) { throw new IllegalArgumentException ( "must map at least one port" ) ; } }


Input: Creates a directory for the user and a series of sub - directories . The root directory is the parent for the user directory . The sub - directories are confidential and shared . The ROLE_USER will be given read and write access to shared . [CODESPLIT] private void createSampleData ( String username , String password ) { Assert . notNull ( documentDao , "DocumentDao required" ) ; Assert . hasText ( username , "Username required" ) ; Authentication auth = new UsernamePasswordAuthenticationToken ( username , password ) ; try { // Set the SecurityContextHolder ThreadLocal so any subclasses // automatically know which user is operating SecurityContextHolder . getContext ( ) . setAuthentication ( auth ) ; // Create the home directory first Directory home = new Directory ( username , Directory . ROOT_DIRECTORY ) ; documentDao . create ( home ) ; addPermission ( documentDao , home , username , LEVEL_GRANT_ADMIN ) ; addPermission ( documentDao , home , "ROLE_USER" , LEVEL_GRANT_READ ) ; createFiles ( documentDao , home ) ; // Now create the confidential directory Directory confid = new Directory ( "confidential" , home ) ; documentDao . create ( confid ) ; addPermission ( documentDao , confid , "ROLE_USER" , LEVEL_NEGATE_READ ) ; createFiles ( documentDao , confid ) ; // Now create the shared directory Directory shared = new Directory ( "shared" , home ) ; documentDao . create ( shared ) ; addPermission ( documentDao , shared , "ROLE_USER" , LEVEL_GRANT_READ ) ; addPermission ( documentDao , shared , "ROLE_USER" , LEVEL_GRANT_WRITE ) ; createFiles ( documentDao , shared ) ; } finally { // Clear the SecurityContextHolder ThreadLocal so future calls are // guaranteed to be clean SecurityContextHolder . clearContext ( ) ; } }


Input: Sets the algorithm to use . See <a href = https : // docs . oracle . com / javase / 8 / docs / technotes / guides / security / StandardNames . html#SecretKeyFactory > SecretKeyFactory Algorithms< / a > [CODESPLIT] public void setAlgorithm ( SecretKeyFactoryAlgorithm secretKeyFactoryAlgorithm ) { if ( secretKeyFactoryAlgorithm == null ) { throw new IllegalArgumentException ( "secretKeyFactoryAlgorithm cannot be null" ) ; } String algorithmName = secretKeyFactoryAlgorithm . name ( ) ; try { SecretKeyFactory . getInstance ( algorithmName ) ; } catch ( NoSuchAlgorithmException e ) { throw new IllegalArgumentException ( "Invalid algorithm '" + algorithmName + "'." , e ) ; } this . algorithm = algorithmName ; }


Input: If the callback passed to the handle method is an instance of PasswordCallback the JaasPasswordCallbackHandler will call callback . setPassword ( authentication . getCredentials () . toString () ) . [CODESPLIT] public void handle ( Callback callback , Authentication auth ) throws IOException , UnsupportedCallbackException { if ( callback instanceof PasswordCallback ) { PasswordCallback pc = ( PasswordCallback ) callback ; pc . setPassword ( auth . getCredentials ( ) . toString ( ) . toCharArray ( ) ) ; } }


Input: Provides a save way of obtaining the HttpMethod from a String . If the method is invalid returns null . [CODESPLIT] private static HttpMethod valueOf ( String method ) { try { return HttpMethod . valueOf ( method ) ; } catch ( IllegalArgumentException e ) { } return null ; }


Input: ======================================================================================================== [CODESPLIT] public void doFilter ( ServletRequest req , ServletResponse res , FilterChain chain ) throws IOException , ServletException { HttpServletRequest request = ( HttpServletRequest ) req ; HttpServletResponse response = ( HttpServletResponse ) res ; if ( requiresLogout ( request , response ) ) { Authentication auth = SecurityContextHolder . getContext ( ) . getAuthentication ( ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Logging out user '" + auth + "' and transferring to logout destination" ) ; } this . handler . logout ( request , response , auth ) ; logoutSuccessHandler . onLogoutSuccess ( request , response , auth ) ; return ; } chain . doFilter ( request , response ) ; }


Input: Return the LdapUserDetails containing the user s information [CODESPLIT] @ Override public DirContextOperations searchForUser ( String username ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Searching for user '" + username + "', with user search " + this ) ; } SpringSecurityLdapTemplate template = new SpringSecurityLdapTemplate ( contextSource ) ; template . setSearchControls ( searchControls ) ; try { return template . searchForSingleEntry ( searchBase , searchFilter , new String [ ] { username } ) ; } catch ( IncorrectResultSizeDataAccessException notFound ) { if ( notFound . getActualSize ( ) == 0 ) { throw new UsernameNotFoundException ( "User " + username + " not found in directory." ) ; } // Search should never return multiple results if properly configured, so just // rethrow throw notFound ; } }


Input: ======================================================================================================== [CODESPLIT] public String beginConsumption ( HttpServletRequest req , String identityUrl , String returnToUrl , String realm ) throws OpenIDConsumerException { List < DiscoveryInformation > discoveries ; try { discoveries = consumerManager . discover ( identityUrl ) ; } catch ( DiscoveryException e ) { throw new OpenIDConsumerException ( "Error during discovery" , e ) ; } DiscoveryInformation information = consumerManager . associate ( discoveries ) ; req . getSession ( ) . setAttribute ( DISCOVERY_INFO_KEY , information ) ; AuthRequest authReq ; try { authReq = consumerManager . authenticate ( information , returnToUrl , realm ) ; logger . debug ( "Looking up attribute fetch list for identifier: " + identityUrl ) ; List < OpenIDAttribute > attributesToFetch = attributesToFetchFactory . createAttributeList ( identityUrl ) ; if ( ! attributesToFetch . isEmpty ( ) ) { req . getSession ( ) . setAttribute ( ATTRIBUTE_LIST_KEY , attributesToFetch ) ; FetchRequest fetchRequest = FetchRequest . createFetchRequest ( ) ; for ( OpenIDAttribute attr : attributesToFetch ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Adding attribute " + attr . getType ( ) + " to fetch request" ) ; } fetchRequest . addAttribute ( attr . getName ( ) , attr . getType ( ) , attr . isRequired ( ) , attr . getCount ( ) ) ; } authReq . addExtension ( fetchRequest ) ; } } catch ( MessageException e ) { throw new OpenIDConsumerException ( "Error processing ConsumerManager authentication" , e ) ; } catch ( ConsumerException e ) { throw new OpenIDConsumerException ( "Error processing ConsumerManager authentication" , e ) ; } return authReq . getDestinationUrl ( true ) ; }


Input: Encodes the rawPass using a MessageDigest . If a salt is specified it will be merged with the password before encoding . [CODESPLIT] public String encode ( CharSequence rawPassword ) { String salt = PREFIX + this . saltGenerator . generateKey ( ) + SUFFIX ; return digest ( salt , rawPassword ) ; }


Input: Takes a previously encoded password and compares it with a rawpassword after mixing in the salt and encoding that value [CODESPLIT] public boolean matches ( CharSequence rawPassword , String encodedPassword ) { String salt = extractSalt ( encodedPassword ) ; String rawPasswordEncoded = digest ( salt , rawPassword ) ; return PasswordEncoderUtils . equals ( encodedPassword . toString ( ) , rawPasswordEncoded ) ; }


Input: Perform version checks with specific min Spring Version [CODESPLIT] private static void performVersionChecks ( String minSpringVersion ) { if ( minSpringVersion == null ) { return ; } // Check Spring Compatibility String springVersion = SpringVersion . getVersion ( ) ; String version = getVersion ( ) ; if ( disableChecks ( springVersion , version ) ) { return ; } logger . info ( "You are running with Spring Security Core " + version ) ; if ( new ComparableVersion ( springVersion ) . compareTo ( new ComparableVersion ( minSpringVersion ) ) < 0 ) { logger . warn ( "**** You are advised to use Spring " + minSpringVersion + " or later with this version. You are running: " + springVersion ) ; } }


Input: Disable if springVersion and springSecurityVersion are the same to allow working with Uber Jars . [CODESPLIT] private static boolean disableChecks ( String springVersion , String springSecurityVersion ) { if ( springVersion == null || springVersion . equals ( springSecurityVersion ) ) { return true ; } return Boolean . getBoolean ( DISABLE_CHECKS ) ; }


Input: Loads the spring version or null if it cannot be found . [CODESPLIT] private static String getSpringVersion ( ) { Properties properties = new Properties ( ) ; try { properties . load ( SpringSecurityCoreVersion . class . getClassLoader ( ) . getResourceAsStream ( "META-INF/spring-security.versions" ) ) ; } catch ( IOException | NullPointerException e ) { return null ; } return properties . getProperty ( "org.springframework:spring-core" ) ; }


Input: Attempts to load the client registration id from the current { [CODESPLIT] private Mono < String > clientRegistrationId ( Mono < Authentication > authentication ) { return authentication . filter ( t -> this . defaultOAuth2AuthorizedClient && t instanceof OAuth2AuthenticationToken ) . cast ( OAuth2AuthenticationToken . class ) . map ( OAuth2AuthenticationToken :: getAuthorizedClientRegistrationId ) ; }


Input: Iterates through all <code > AfterInvocationProvider< / code > s and ensures each can support the presented class . <p > If one or more providers cannot support the presented class <code > false< / code > is returned . [CODESPLIT] public boolean supports ( Class < ? > clazz ) { for ( AfterInvocationProvider provider : providers ) { if ( ! provider . supports ( clazz ) ) { return false ; } } return true ; }


Input: Shortcut for invoking { @link #authenticationUserDetailsService ( AuthenticationUserDetailsService ) } with a { @link UserDetailsByNameServiceWrapper } . [CODESPLIT] public X509Configurer < H > userDetailsService ( UserDetailsService userDetailsService ) { UserDetailsByNameServiceWrapper < PreAuthenticatedAuthenticationToken > authenticationUserDetailsService = new UserDetailsByNameServiceWrapper <> ( ) ; authenticationUserDetailsService . setUserDetailsService ( userDetailsService ) ; return authenticationUserDetailsService ( authenticationUserDetailsService ) ; }


Input: Specifies the regex to extract the principal from the certificate . If not specified the default expression from { @link SubjectDnX509PrincipalExtractor } is used . [CODESPLIT] public X509Configurer < H > subjectPrincipalRegex ( String subjectPrincipalRegex ) { SubjectDnX509PrincipalExtractor principalExtractor = new SubjectDnX509PrincipalExtractor ( ) ; principalExtractor . setSubjectDnRegex ( subjectPrincipalRegex ) ; this . x509PrincipalExtractor = principalExtractor ; return this ; }


Input: / * ( non - Javadoc ) [CODESPLIT] public final O build ( ) throws Exception { if ( this . building . compareAndSet ( false , true ) ) { this . object = doBuild ( ) ; return this . object ; } throw new AlreadyBuiltException ( "This object has already been built" ) ; }


Input: ======================================================================================================== [CODESPLIT] public final Collection < ConfigAttribute > getAttributes ( Object object ) { if ( object instanceof MethodInvocation ) { MethodInvocation mi = ( MethodInvocation ) object ; Object target = mi . getThis ( ) ; Class < ? > targetClass = null ; if ( target != null ) { targetClass = target instanceof Class < ? > ? ( Class < ? > ) target : AopProxyUtils . ultimateTargetClass ( target ) ; } Collection < ConfigAttribute > attrs = getAttributes ( mi . getMethod ( ) , targetClass ) ; if ( attrs != null && ! attrs . isEmpty ( ) ) { return attrs ; } if ( target != null && ! ( target instanceof Class < ? > ) ) { attrs = getAttributes ( mi . getMethod ( ) , target . getClass ( ) ) ; } return attrs ; } throw new IllegalArgumentException ( "Object must be a non-null MethodInvocation" ) ; }


Input: Gets a non - null and mutable map of { [CODESPLIT] private Map < String , OAuth2AuthorizationRequest > getAuthorizationRequests ( HttpServletRequest request ) { HttpSession session = request . getSession ( false ) ; Map < String , OAuth2AuthorizationRequest > authorizationRequests = session == null ? null : ( Map < String , OAuth2AuthorizationRequest > ) session . getAttribute ( this . sessionAttributeName ) ; if ( authorizationRequests == null ) { return new HashMap <> ( ) ; } return authorizationRequests ; }


Input: ======================================================================================================== [CODESPLIT] public void logIfNeeded ( boolean granted , AccessControlEntry ace ) { Assert . notNull ( ace , "AccessControlEntry required" ) ; if ( ace instanceof AuditableAccessControlEntry ) { AuditableAccessControlEntry auditableAce = ( AuditableAccessControlEntry ) ace ; if ( granted && auditableAce . isAuditSuccess ( ) ) { System . out . println ( "GRANTED due to ACE: " + ace ) ; } else if ( ! granted && auditableAce . isAuditFailure ( ) ) { System . out . println ( "DENIED due to ACE: " + ace ) ; } } }


Input: Sets up OpenID attribute exchange for OpenID s matching the specified pattern . [CODESPLIT] public AttributeExchangeConfigurer attributeExchange ( String identifierPattern ) { AttributeExchangeConfigurer attributeExchangeConfigurer = new AttributeExchangeConfigurer ( identifierPattern ) ; this . attributeExchangeConfigurers . add ( attributeExchangeConfigurer ) ; return attributeExchangeConfigurer ; }


Input: Gets the { [CODESPLIT] private OpenIDConsumer getConsumer ( ) throws ConsumerException { if ( this . openIDConsumer == null ) { this . openIDConsumer = new OpenID4JavaConsumer ( getConsumerManager ( ) , attributesToFetchFactory ( ) ) ; } return this . openIDConsumer ; }


Input: Creates an { @link RegexBasedAxFetchListFactory } using the attributes populated by { @link AttributeExchangeConfigurer } [CODESPLIT] private AxFetchListFactory attributesToFetchFactory ( ) { Map < String , List < OpenIDAttribute > > identityToAttrs = new HashMap < String , List < OpenIDAttribute > > ( ) ; for ( AttributeExchangeConfigurer conf : this . attributeExchangeConfigurers ) { identityToAttrs . put ( conf . identifier , conf . getAttributes ( ) ) ; } return new RegexBasedAxFetchListFactory ( identityToAttrs ) ; }


Input: Gets the { @link AuthenticationUserDetailsService } that was configured or defaults to { @link UserDetailsByNameServiceWrapper } that uses a { @link UserDetailsService } looked up using { @link HttpSecurity#getSharedObject ( Class ) } [CODESPLIT] private AuthenticationUserDetailsService < OpenIDAuthenticationToken > getAuthenticationUserDetailsService ( H http ) { if ( this . authenticationUserDetailsService != null ) { return this . authenticationUserDetailsService ; } return new UserDetailsByNameServiceWrapper <> ( http . getSharedObject ( UserDetailsService . class ) ) ; }


Input: If available initializes the { @link DefaultLoginPageGeneratingFilter } shared object . [CODESPLIT] private void initDefaultLoginFilter ( H http ) { DefaultLoginPageGeneratingFilter loginPageGeneratingFilter = http . getSharedObject ( DefaultLoginPageGeneratingFilter . class ) ; if ( loginPageGeneratingFilter != null && ! isCustomLoginPage ( ) ) { loginPageGeneratingFilter . setOpenIdEnabled ( true ) ; loginPageGeneratingFilter . setOpenIDauthenticationUrl ( getLoginProcessingUrl ( ) ) ; String loginPageUrl = loginPageGeneratingFilter . getLoginPageUrl ( ) ; if ( loginPageUrl == null ) { loginPageGeneratingFilter . setLoginPageUrl ( getLoginPage ( ) ) ; loginPageGeneratingFilter . setFailureUrl ( getFailureUrl ( ) ) ; } loginPageGeneratingFilter . setOpenIDusernameParameter ( OpenIDAuthenticationFilter . DEFAULT_CLAIMED_IDENTITY_FIELD ) ; } }


Input: Allows restricting access based upon the { @link HttpServletRequest } using [CODESPLIT] public ExpressionUrlAuthorizationConfigurer < HttpSecurity > . ExpressionInterceptUrlRegistry authorizeRequests ( ) throws Exception { ApplicationContext context = getContext ( ) ; return getOrApply ( new ExpressionUrlAuthorizationConfigurer <> ( context ) ) . getRegistry ( ) ; }


Input: Adds CSRF support . This is activated by default when using { @link WebSecurityConfigurerAdapter } s default constructor . You can disable it using : [CODESPLIT] public CsrfConfigurer < HttpSecurity > csrf ( ) throws Exception { ApplicationContext context = getContext ( ) ; return getOrApply ( new CsrfConfigurer <> ( context ) ) ; }


Input: Configures OAuth 2 . 0 Client support . [CODESPLIT] public OAuth2ClientConfigurer < HttpSecurity > oauth2Client ( ) throws Exception { OAuth2ClientConfigurer < HttpSecurity > configurer = getOrApply ( new OAuth2ClientConfigurer <> ( ) ) ; this . postProcess ( configurer ) ; return configurer ; }


Input: Configures OAuth 2 . 0 Resource Server support . [CODESPLIT] public OAuth2ResourceServerConfigurer < HttpSecurity > oauth2ResourceServer ( ) throws Exception { OAuth2ResourceServerConfigurer < HttpSecurity > configurer = getOrApply ( new OAuth2ResourceServerConfigurer <> ( getContext ( ) ) ) ; this . postProcess ( configurer ) ; return configurer ; }


Input: Configures channel security . In order for this configuration to be useful at least one mapping to a required channel must be provided . [CODESPLIT] public ChannelSecurityConfigurer < HttpSecurity > . ChannelRequestMatcherRegistry requiresChannel ( ) throws Exception { ApplicationContext context = getContext ( ) ; return getOrApply ( new ChannelSecurityConfigurer <> ( context ) ) . getRegistry ( ) ; }


Input: / * ( non - Javadoc ) [CODESPLIT] public HttpSecurity addFilterAfter ( Filter filter , Class < ? extends Filter > afterFilter ) { comparator . registerAfter ( filter . getClass ( ) , afterFilter ) ; return addFilter ( filter ) ; }


Input: / * ( non - Javadoc ) [CODESPLIT] public HttpSecurity addFilterBefore ( Filter filter , Class < ? extends Filter > beforeFilter ) { comparator . registerBefore ( filter . getClass ( ) , beforeFilter ) ; return addFilter ( filter ) ; }


Input: / * ( non - Javadoc ) [CODESPLIT] public HttpSecurity addFilter ( Filter filter ) { Class < ? extends Filter > filterClass = filter . getClass ( ) ; if ( ! comparator . isRegistered ( filterClass ) ) { throw new IllegalArgumentException ( "The Filter class " + filterClass . getName ( ) + " does not have a registered order and cannot be added without a specified order. Consider using addFilterBefore or addFilterAfter instead." ) ; } this . filters . add ( filter ) ; return this ; }


Input: Adds the Filter at the location of the specified Filter class . For example if you want the filter CustomFilter to be registered in the same position as { @link UsernamePasswordAuthenticationFilter } you can invoke : [CODESPLIT] public HttpSecurity addFilterAt ( Filter filter , Class < ? extends Filter > atFilter ) { this . comparator . registerAt ( filter . getClass ( ) , atFilter ) ; return addFilter ( filter ) ; }


Input: Allows configuring the { @link HttpSecurity } to only be invoked when matching the provided Spring MVC pattern . If more advanced configuration is necessary consider using { @link #requestMatchers () } or { @link #requestMatcher ( RequestMatcher ) } . [CODESPLIT] public HttpSecurity mvcMatcher ( String mvcPattern ) { HandlerMappingIntrospector introspector = new HandlerMappingIntrospector ( getContext ( ) ) ; return requestMatcher ( new MvcRequestMatcher ( introspector , mvcPattern ) ) ; }


Input: If the { @link SecurityConfigurer } has already been specified get the original otherwise apply the new { @link SecurityConfigurerAdapter } . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) private < C extends SecurityConfigurerAdapter < DefaultSecurityFilterChain , HttpSecurity > > C getOrApply ( C configurer ) throws Exception { C existingConfig = ( C ) getConfigurer ( configurer . getClass ( ) ) ; if ( existingConfig != null ) { return existingConfig ; } return apply ( configurer ) ; }


Input: Maps a { @link List } of { @link PathPatternParserServerWebExchangeMatcher } instances . [CODESPLIT] public T pathMatchers ( HttpMethod method , String ... antPatterns ) { return matcher ( ServerWebExchangeMatchers . pathMatchers ( method , antPatterns ) ) ; }


Input: Performs an LDAP compare operation of the value of an attribute for a particular directory entry . [CODESPLIT] public boolean compare ( final String dn , final String attributeName , final Object value ) { final String comparisonFilter = "(" + attributeName + "={0})" ; class LdapCompareCallback implements ContextExecutor { public Object executeWithContext ( DirContext ctx ) throws NamingException { SearchControls ctls = new SearchControls ( ) ; ctls . setReturningAttributes ( NO_ATTRS ) ; ctls . setSearchScope ( SearchControls . OBJECT_SCOPE ) ; NamingEnumeration < SearchResult > results = ctx . search ( dn , comparisonFilter , new Object [ ] { value } , ctls ) ; Boolean match = Boolean . valueOf ( results . hasMore ( ) ) ; LdapUtils . closeEnumeration ( results ) ; return match ; } } Boolean matches = ( Boolean ) executeReadOnly ( new LdapCompareCallback ( ) ) ; return matches . booleanValue ( ) ; }


Input: Composes an object from the attributes of the given DN . [CODESPLIT] public DirContextOperations retrieveEntry ( final String dn , final String [ ] attributesToRetrieve ) { return ( DirContextOperations ) executeReadOnly ( new ContextExecutor ( ) { public Object executeWithContext ( DirContext ctx ) throws NamingException { Attributes attrs = ctx . getAttributes ( dn , attributesToRetrieve ) ; // Object object = ctx.lookup(LdapUtils.getRelativeName(dn, ctx)); return new DirContextAdapter ( attrs , new DistinguishedName ( dn ) , new DistinguishedName ( ctx . getNameInNamespace ( ) ) ) ; } } ) ; }


Input: Performs a search using the supplied filter and returns the union of the values of the named attribute found in all entries matched by the search . Note that one directory entry may have several values for the attribute . Intended for role searches and similar scenarios . [CODESPLIT] public Set < String > searchForSingleAttributeValues ( final String base , final String filter , final Object [ ] params , final String attributeName ) { String [ ] attributeNames = new String [ ] { attributeName } ; Set < Map < String , List < String > > > multipleAttributeValues = searchForMultipleAttributeValues ( base , filter , params , attributeNames ) ; Set < String > result = new HashSet <> ( ) ; for ( Map < String , List < String > > map : multipleAttributeValues ) { List < String > values = map . get ( attributeName ) ; if ( values != null ) { result . addAll ( values ) ; } } return result ; }


Input: Performs a search using the supplied filter and returns the values of each named attribute found in all entries matched by the search . Note that one directory entry may have several values for the attribute . Intended for role searches and similar scenarios . [CODESPLIT] public Set < Map < String , List < String > > > searchForMultipleAttributeValues ( final String base , final String filter , final Object [ ] params , final String [ ] attributeNames ) { // Escape the params acording to RFC2254 Object [ ] encodedParams = new String [ params . length ] ; for ( int i = 0 ; i < params . length ; i ++ ) { encodedParams [ i ] = LdapEncoder . filterEncode ( params [ i ] . toString ( ) ) ; } String formattedFilter = MessageFormat . format ( filter , encodedParams ) ; logger . debug ( "Using filter: " + formattedFilter ) ; final HashSet < Map < String , List < String > > > set = new HashSet < Map < String , List < String > > > ( ) ; ContextMapper roleMapper = new ContextMapper ( ) { public Object mapFromContext ( Object ctx ) { DirContextAdapter adapter = ( DirContextAdapter ) ctx ; Map < String , List < String > > record = new HashMap < String , List < String > > ( ) ; if ( attributeNames == null || attributeNames . length == 0 ) { try { for ( NamingEnumeration ae = adapter . getAttributes ( ) . getAll ( ) ; ae . hasMore ( ) ; ) { Attribute attr = ( Attribute ) ae . next ( ) ; extractStringAttributeValues ( adapter , record , attr . getID ( ) ) ; } } catch ( NamingException x ) { org . springframework . ldap . support . LdapUtils . convertLdapException ( x ) ; } } else { for ( String attributeName : attributeNames ) { extractStringAttributeValues ( adapter , record , attributeName ) ; } } record . put ( DN_KEY , Arrays . asList ( getAdapterDN ( adapter ) ) ) ; set . add ( record ) ; return null ; } } ; SearchControls ctls = new SearchControls ( ) ; ctls . setSearchScope ( searchControls . getSearchScope ( ) ) ; ctls . setReturningAttributes ( attributeNames != null && attributeNames . length > 0 ? attributeNames : null ) ; search ( base , formattedFilter , ctls , roleMapper ) ; return set ; }


Input: Extracts String values for a specified attribute name and places them in the map representing the ldap record If a value is not of type String it will derive it s value from the { @link Object#toString () } [CODESPLIT] private void extractStringAttributeValues ( DirContextAdapter adapter , Map < String , List < String > > record , String attributeName ) { Object [ ] values = adapter . getObjectAttributes ( attributeName ) ; if ( values == null || values . length == 0 ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "No attribute value found for '" + attributeName + "'" ) ; } return ; } List < String > svalues = new ArrayList <> ( ) ; for ( Object o : values ) { if ( o != null ) { if ( String . class . isAssignableFrom ( o . getClass ( ) ) ) { svalues . add ( ( String ) o ) ; } else { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Attribute:" + attributeName + " contains a non string value of type[" + o . getClass ( ) + "]" ) ; } svalues . add ( o . toString ( ) ) ; } } } record . put ( attributeName , svalues ) ; }


Input: Performs a search with the requirement that the search shall return a single directory entry and uses the supplied mapper to create the object from that entry . <p > Ignores <tt > PartialResultException< / tt > if thrown for compatibility with Active Directory ( see { @link LdapTemplate#setIgnorePartialResultException ( boolean ) } ) . [CODESPLIT] public DirContextOperations searchForSingleEntry ( final String base , final String filter , final Object [ ] params ) { return ( DirContextOperations ) executeReadOnly ( new ContextExecutor ( ) { public Object executeWithContext ( DirContext ctx ) throws NamingException { return searchForSingleEntryInternal ( ctx , searchControls , base , filter , params ) ; } } ) ; }


Input: Internal method extracted to avoid code duplication in AD search . [CODESPLIT] public static DirContextOperations searchForSingleEntryInternal ( DirContext ctx , SearchControls searchControls , String base , String filter , Object [ ] params ) throws NamingException { final DistinguishedName ctxBaseDn = new DistinguishedName ( ctx . getNameInNamespace ( ) ) ; final DistinguishedName searchBaseDn = new DistinguishedName ( base ) ; final NamingEnumeration < SearchResult > resultsEnum = ctx . search ( searchBaseDn , filter , params , buildControls ( searchControls ) ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Searching for entry under DN '" + ctxBaseDn + "', base = '" + searchBaseDn + "', filter = '" + filter + "'" ) ; } Set < DirContextOperations > results = new HashSet <> ( ) ; try { while ( resultsEnum . hasMore ( ) ) { SearchResult searchResult = resultsEnum . next ( ) ; DirContextAdapter dca = ( DirContextAdapter ) searchResult . getObject ( ) ; Assert . notNull ( dca , "No object returned by search, DirContext is not correctly configured" ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Found DN: " + dca . getDn ( ) ) ; } results . add ( dca ) ; } } catch ( PartialResultException e ) { LdapUtils . closeEnumeration ( resultsEnum ) ; logger . info ( "Ignoring PartialResultException" ) ; } if ( results . size ( ) == 0 ) { throw new IncorrectResultSizeDataAccessException ( 1 , 0 ) ; } if ( results . size ( ) > 1 ) { throw new IncorrectResultSizeDataAccessException ( 1 , results . size ( ) ) ; } return results . iterator ( ) . next ( ) ; }


Input: We need to make sure the search controls has the return object flag set to true in order for the search to return DirContextAdapter instances . [CODESPLIT] private static SearchControls buildControls ( SearchControls originalControls ) { return new SearchControls ( originalControls . getSearchScope ( ) , originalControls . getCountLimit ( ) , originalControls . getTimeLimit ( ) , originalControls . getReturningAttributes ( ) , RETURN_OBJECT , originalControls . getDerefLinkFlag ( ) ) ; }


Input: ======================================================================================================== [CODESPLIT] private String computeRepeatingSql ( String repeatingSql , int requiredRepetitions ) { assert requiredRepetitions > 0 : "requiredRepetitions must be > 0" ; final String startSql = selectClause ; final String endSql = orderByClause ; StringBuilder sqlStringBldr = new StringBuilder ( startSql . length ( ) + endSql . length ( ) + requiredRepetitions * ( repeatingSql . length ( ) + 4 ) ) ; sqlStringBldr . append ( startSql ) ; for ( int i = 1 ; i <= requiredRepetitions ; i ++ ) { sqlStringBldr . append ( repeatingSql ) ; if ( i != requiredRepetitions ) { sqlStringBldr . append ( " or " ) ; } } sqlStringBldr . append ( endSql ) ; return sqlStringBldr . toString ( ) ; }


Input: Locates the primary key IDs specified in findNow adding AclImpl instances with StubAclParents to the acls Map . [CODESPLIT] private void lookupPrimaryKeys ( final Map < Serializable , Acl > acls , final Set < Long > findNow , final List < Sid > sids ) { Assert . notNull ( acls , "ACLs are required" ) ; Assert . notEmpty ( findNow , "Items to find now required" ) ; String sql = computeRepeatingSql ( lookupPrimaryKeysWhereClause , findNow . size ( ) ) ; Set < Long > parentsToLookup = jdbcTemplate . query ( sql , new PreparedStatementSetter ( ) { public void setValues ( PreparedStatement ps ) throws SQLException { int i = 0 ; for ( Long toFind : findNow ) { i ++ ; ps . setLong ( i , toFind ) ; } } } , new ProcessResultSet ( acls , sids ) ) ; // Lookup the parents, now that our JdbcTemplate has released the database // connection (SEC-547) if ( parentsToLookup . size ( ) > 0 ) { lookupPrimaryKeys ( acls , parentsToLookup , sids ) ; } }


Input: The main method . <p > WARNING : This implementation completely disregards the sids argument! Every item in the cache is expected to contain all SIDs . If you have serious performance needs ( e . g . a very large number of SIDs per object identity ) you ll probably want to develop a custom { @link LookupStrategy } implementation instead . <p > The implementation works in batch sizes specified by { @link #batchSize } . [CODESPLIT] public final Map < ObjectIdentity , Acl > readAclsById ( List < ObjectIdentity > objects , List < Sid > sids ) { Assert . isTrue ( batchSize >= 1 , "BatchSize must be >= 1" ) ; Assert . notEmpty ( objects , "Objects to lookup required" ) ; // Map<ObjectIdentity,Acl> Map < ObjectIdentity , Acl > result = new HashMap <> ( ) ; // contains // FULLY // loaded // Acl // objects Set < ObjectIdentity > currentBatchToLoad = new HashSet <> ( ) ; for ( int i = 0 ; i < objects . size ( ) ; i ++ ) { final ObjectIdentity oid = objects . get ( i ) ; boolean aclFound = false ; // Check we don't already have this ACL in the results if ( result . containsKey ( oid ) ) { aclFound = true ; } // Check cache for the present ACL entry if ( ! aclFound ) { Acl acl = aclCache . getFromCache ( oid ) ; // Ensure any cached element supports all the requested SIDs // (they should always, as our base impl doesn't filter on SID) if ( acl != null ) { if ( acl . isSidLoaded ( sids ) ) { result . put ( acl . getObjectIdentity ( ) , acl ) ; aclFound = true ; } else { throw new IllegalStateException ( "Error: SID-filtered element detected when implementation does not perform SID filtering " + "- have you added something to the cache manually?" ) ; } } } // Load the ACL from the database if ( ! aclFound ) { currentBatchToLoad . add ( oid ) ; } // Is it time to load from JDBC the currentBatchToLoad? if ( ( currentBatchToLoad . size ( ) == this . batchSize ) || ( ( i + 1 ) == objects . size ( ) ) ) { if ( currentBatchToLoad . size ( ) > 0 ) { Map < ObjectIdentity , Acl > loadedBatch = lookupObjectIdentities ( currentBatchToLoad , sids ) ; // Add loaded batch (all elements 100% initialized) to results result . putAll ( loadedBatch ) ; // Add the loaded batch to the cache for ( Acl loadedAcl : loadedBatch . values ( ) ) { aclCache . putInCache ( ( AclImpl ) loadedAcl ) ; } currentBatchToLoad . clear ( ) ; } } } return result ; }


Input: Looks up a batch of <code > ObjectIdentity< / code > s directly from the database . <p > The caller is responsible for optimization issues such as selecting the identities to lookup ensuring the cache doesn t contain them already and adding the returned elements to the cache etc . <p > This subclass is required to return fully valid <code > Acl< / code > s including properly - configured parent ACLs . [CODESPLIT] private Map < ObjectIdentity , Acl > lookupObjectIdentities ( final Collection < ObjectIdentity > objectIdentities , List < Sid > sids ) { Assert . notEmpty ( objectIdentities , "Must provide identities to lookup" ) ; final Map < Serializable , Acl > acls = new HashMap <> ( ) ; // contains // Acls // with // StubAclParents // Make the "acls" map contain all requested objectIdentities // (including markers to each parent in the hierarchy) String sql = computeRepeatingSql ( lookupObjectIdentitiesWhereClause , objectIdentities . size ( ) ) ; Set < Long > parentsToLookup = jdbcTemplate . query ( sql , new PreparedStatementSetter ( ) { public void setValues ( PreparedStatement ps ) throws SQLException { int i = 0 ; for ( ObjectIdentity oid : objectIdentities ) { // Determine prepared statement values for this iteration String type = oid . getType ( ) ; // No need to check for nulls, as guaranteed non-null by // ObjectIdentity.getIdentifier() interface contract String identifier = oid . getIdentifier ( ) . toString ( ) ; // Inject values ps . setString ( ( 2 * i ) + 1 , identifier ) ; ps . setString ( ( 2 * i ) + 2 , type ) ; i ++ ; } } } , new ProcessResultSet ( acls , sids ) ) ; // Lookup the parents, now that our JdbcTemplate has released the database // connection (SEC-547) if ( parentsToLookup . size ( ) > 0 ) { lookupPrimaryKeys ( acls , parentsToLookup , sids ) ; } // Finally, convert our "acls" containing StubAclParents into true Acls Map < ObjectIdentity , Acl > resultMap = new HashMap <> ( ) ; for ( Acl inputAcl : acls . values ( ) ) { Assert . isInstanceOf ( AclImpl . class , inputAcl , "Map should have contained an AclImpl" ) ; Assert . isInstanceOf ( Long . class , ( ( AclImpl ) inputAcl ) . getId ( ) , "Acl.getId() must be Long" ) ; Acl result = convert ( acls , ( Long ) ( ( AclImpl ) inputAcl ) . getId ( ) ) ; resultMap . put ( result . getObjectIdentity ( ) , result ) ; } return resultMap ; }


Input: The final phase of converting the <code > Map< / code > of <code > AclImpl< / code > instances which contain <code > StubAclParent< / code > s into proper valid <code > AclImpl< / code > s with correct ACL parents . [CODESPLIT] private AclImpl convert ( Map < Serializable , Acl > inputMap , Long currentIdentity ) { Assert . notEmpty ( inputMap , "InputMap required" ) ; Assert . notNull ( currentIdentity , "CurrentIdentity required" ) ; // Retrieve this Acl from the InputMap Acl uncastAcl = inputMap . get ( currentIdentity ) ; Assert . isInstanceOf ( AclImpl . class , uncastAcl , "The inputMap contained a non-AclImpl" ) ; AclImpl inputAcl = ( AclImpl ) uncastAcl ; Acl parent = inputAcl . getParentAcl ( ) ; if ( ( parent != null ) && parent instanceof StubAclParent ) { // Lookup the parent StubAclParent stubAclParent = ( StubAclParent ) parent ; parent = convert ( inputMap , stubAclParent . getId ( ) ) ; } // Now we have the parent (if there is one), create the true AclImpl AclImpl result = new AclImpl ( inputAcl . getObjectIdentity ( ) , ( Long ) inputAcl . getId ( ) , aclAuthorizationStrategy , grantingStrategy , parent , null , inputAcl . isEntriesInheriting ( ) , inputAcl . getOwner ( ) ) ; // Copy the "aces" from the input to the destination // Obtain the "aces" from the input ACL List < AccessControlEntryImpl > aces = readAces ( inputAcl ) ; // Create a list in which to store the "aces" for the "result" AclImpl instance List < AccessControlEntryImpl > acesNew = new ArrayList <> ( ) ; // Iterate over the "aces" input and replace each nested // AccessControlEntryImpl.getAcl() with the new "result" AclImpl instance // This ensures StubAclParent instances are removed, as per SEC-951 for ( AccessControlEntryImpl ace : aces ) { setAclOnAce ( ace , result ) ; acesNew . add ( ace ) ; } // Finally, now that the "aces" have been converted to have the "result" AclImpl // instance, modify the "result" AclImpl instance setAces ( result , acesNew ) ; return result ; }


Input: Creates a particular implementation of { @link Sid } depending on the arguments . [CODESPLIT] protected Sid createSid ( boolean isPrincipal , String sid ) { if ( isPrincipal ) { return new PrincipalSid ( sid ) ; } else { return new GrantedAuthoritySid ( sid ) ; } }


Input: Obtains the list of user roles based on the current user s JEE roles . The { @link javax . servlet . http . HttpServletRequest#isUserInRole ( String ) } method is called for each of the values in the { @code j2eeMappableRoles } set to determine if that role should be assigned to the user . [CODESPLIT] protected Collection < String > getUserRoles ( HttpServletRequest request ) { ArrayList < String > j2eeUserRolesList = new ArrayList <> ( ) ; for ( String role : j2eeMappableRoles ) { if ( request . isUserInRole ( role ) ) { j2eeUserRolesList . add ( role ) ; } } return j2eeUserRolesList ; }


Input: Builds the authentication details object . [CODESPLIT] public PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails buildDetails ( HttpServletRequest context ) { Collection < String > j2eeUserRoles = getUserRoles ( context ) ; Collection < ? extends GrantedAuthority > userGas = j2eeUserRoles2GrantedAuthoritiesMapper . getGrantedAuthorities ( j2eeUserRoles ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "J2EE roles [" + j2eeUserRoles + "] mapped to Granted Authorities: [" + userGas + "]" ) ; } PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails result = new PreAuthenticatedGrantedAuthoritiesWebAuthenticationDetails ( context , userGas ) ; return result ; }


Input: Sets the factory that provides an { @link OAuth2TokenValidator } which is used by the { @link JwtDecoder } . The default is { @link OidcIdTokenValidator } . [CODESPLIT] public final void setJwtValidatorFactory ( Function < ClientRegistration , OAuth2TokenValidator < Jwt > > jwtValidatorFactory ) { Assert . notNull ( jwtValidatorFactory , "jwtValidatorFactory cannot be null" ) ; this . jwtValidatorFactory = jwtValidatorFactory ; }


Input: Sets the resolver that provides the expected { @link JwsAlgorithm JWS algorithm } used for the signature or MAC on the { @link OidcIdToken ID Token } . The default resolves to { @link SignatureAlgorithm#RS256 RS256 } for all { @link ClientRegistration clients } . [CODESPLIT] public final void setJwsAlgorithmResolver ( Function < ClientRegistration , JwsAlgorithm > jwsAlgorithmResolver ) { Assert . notNull ( jwsAlgorithmResolver , "jwsAlgorithmResolver cannot be null" ) ; this . jwsAlgorithmResolver = jwsAlgorithmResolver ; }


Input: Will be called if no url attribute is supplied . [CODESPLIT] private RootBeanDefinition createEmbeddedServer ( Element element , ParserContext parserContext ) { Object source = parserContext . extractSource ( element ) ; String suffix = element . getAttribute ( ATT_ROOT_SUFFIX ) ; if ( ! StringUtils . hasText ( suffix ) ) { suffix = OPT_DEFAULT_ROOT_SUFFIX ; } String port = element . getAttribute ( ATT_PORT ) ; if ( ! StringUtils . hasText ( port ) ) { port = getDefaultPort ( ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Using default port of " + port ) ; } } String url = "ldap://127.0.0.1:" + port + "/" + suffix ; BeanDefinitionBuilder contextSource = BeanDefinitionBuilder . rootBeanDefinition ( CONTEXT_SOURCE_CLASS ) ; contextSource . addConstructorArgValue ( url ) ; contextSource . addPropertyValue ( "userDn" , "uid=admin,ou=system" ) ; contextSource . addPropertyValue ( "password" , "secret" ) ; RootBeanDefinition apacheContainer = new RootBeanDefinition ( "org.springframework.security.ldap.server.ApacheDSContainer" , null , null ) ; apacheContainer . setSource ( source ) ; apacheContainer . getConstructorArgumentValues ( ) . addGenericArgumentValue ( suffix ) ; String ldifs = element . getAttribute ( ATT_LDIF_FILE ) ; if ( ! StringUtils . hasText ( ldifs ) ) { ldifs = OPT_DEFAULT_LDIF_FILE ; } apacheContainer . getConstructorArgumentValues ( ) . addGenericArgumentValue ( ldifs ) ; apacheContainer . getPropertyValues ( ) . addPropertyValue ( "port" , port ) ; logger . info ( "Embedded LDAP server bean definition created for URL: " + url ) ; if ( parserContext . getRegistry ( ) . containsBeanDefinition ( BeanIds . EMBEDDED_APACHE_DS ) ) { parserContext . getReaderContext ( ) . error ( "Only one embedded server bean is allowed per application context" , element ) ; } parserContext . getRegistry ( ) . registerBeanDefinition ( BeanIds . EMBEDDED_APACHE_DS , apacheContainer ) ; return ( RootBeanDefinition ) contextSource . getBeanDefinition ( ) ; }


Input: / * ( non - Javadoc ) [CODESPLIT] @ Override public Mono < Void > writeHttpHeaders ( ServerWebExchange exchange ) { return isSecure ( exchange ) ? delegate . writeHttpHeaders ( exchange ) : Mono . empty ( ) ; }


Input: Adds the servlet - api integration filter if required [CODESPLIT] private void createServletApiFilter ( BeanReference authenticationManager ) { final String ATT_SERVLET_API_PROVISION = "servlet-api-provision" ; final String DEF_SERVLET_API_PROVISION = "true" ; String provideServletApi = httpElt . getAttribute ( ATT_SERVLET_API_PROVISION ) ; if ( ! StringUtils . hasText ( provideServletApi ) ) { provideServletApi = DEF_SERVLET_API_PROVISION ; } if ( "true" . equals ( provideServletApi ) ) { servApiFilter = GrantedAuthorityDefaultsParserUtils . registerWithDefaultRolePrefix ( pc , SecurityContextHolderAwareRequestFilterBeanFactory . class ) ; servApiFilter . getPropertyValues ( ) . add ( "authenticationManager" , authenticationManager ) ; } }


Input: Adds the jaas - api integration filter if required [CODESPLIT] private void createJaasApiFilter ( ) { final String ATT_JAAS_API_PROVISION = "jaas-api-provision" ; final String DEF_JAAS_API_PROVISION = "false" ; String provideJaasApi = httpElt . getAttribute ( ATT_JAAS_API_PROVISION ) ; if ( ! StringUtils . hasText ( provideJaasApi ) ) { provideJaasApi = DEF_JAAS_API_PROVISION ; } if ( "true" . equals ( provideJaasApi ) ) { jaasApiFilter = new RootBeanDefinition ( JaasApiIntegrationFilter . class ) ; } }


Input: Parses the intercept - url elements to obtain the map used by channel security . This will be empty unless the <tt > requires - channel< / tt > attribute has been used on a URL path . [CODESPLIT] private ManagedMap < BeanMetadataElement , BeanDefinition > parseInterceptUrlsForChannelSecurity ( ) { ManagedMap < BeanMetadataElement , BeanDefinition > channelRequestMap = new ManagedMap <> ( ) ; for ( Element urlElt : interceptUrls ) { String path = urlElt . getAttribute ( ATT_PATH_PATTERN ) ; String method = urlElt . getAttribute ( ATT_HTTP_METHOD ) ; String matcherRef = urlElt . getAttribute ( ATT_REQUEST_MATCHER_REF ) ; boolean hasMatcherRef = StringUtils . hasText ( matcherRef ) ; if ( ! hasMatcherRef && ! StringUtils . hasText ( path ) ) { pc . getReaderContext ( ) . error ( "pattern attribute cannot be empty or null" , urlElt ) ; } String requiredChannel = urlElt . getAttribute ( ATT_REQUIRES_CHANNEL ) ; if ( StringUtils . hasText ( requiredChannel ) ) { BeanMetadataElement matcher = hasMatcherRef ? new RuntimeBeanReference ( matcherRef ) : matcherType . createMatcher ( pc , path , method ) ; RootBeanDefinition channelAttributes = new RootBeanDefinition ( ChannelAttributeFactory . class ) ; channelAttributes . getConstructorArgumentValues ( ) . addGenericArgumentValue ( requiredChannel ) ; channelAttributes . setFactoryMethodName ( "createChannelAttributes" ) ; channelRequestMap . put ( matcher , channelAttributes ) ; } } return channelRequestMap ; }


Input: / * ( non - Javadoc ) [CODESPLIT] public void writeHeaders ( HttpServletRequest request , HttpServletResponse response ) { if ( this . requestMatcher . matches ( request ) ) { if ( ! response . containsHeader ( HSTS_HEADER_NAME ) ) { response . setHeader ( HSTS_HEADER_NAME , this . hstsHeaderValue ) ; } } else if ( this . logger . isDebugEnabled ( ) ) { this . logger . debug ( "Not injecting HSTS header since it did not match the requestMatcher " + this . requestMatcher ) ; } }


Input: / * ( non - Javadoc ) [CODESPLIT] public String [ ] selectImports ( AnnotationMetadata importingClassMetadata ) { boolean webmvcPresent = ClassUtils . isPresent ( "org.springframework.web.servlet.DispatcherServlet" , getClass ( ) . getClassLoader ( ) ) ; return webmvcPresent ? new String [ ] { "org.springframework.security.config.annotation.web.configuration.WebMvcSecurityConfiguration" } : new String [ ] { } ; }


Input: Invoked on the server - side . <p > The transmitted principal and credentials will be used to create an unauthenticated { @code Authentication } instance for processing by the { @code AuthenticationManager } . [CODESPLIT] public Object invoke ( Object targetObject ) throws NoSuchMethodException , IllegalAccessException , InvocationTargetException { if ( principal != null ) { Authentication request = createAuthenticationRequest ( principal , credentials ) ; request . setAuthenticated ( false ) ; SecurityContextHolder . getContext ( ) . setAuthentication ( request ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Set SecurityContextHolder to contain: " + request ) ; } } try { return super . invoke ( targetObject ) ; } finally { SecurityContextHolder . clearContext ( ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Cleared SecurityContextHolder." ) ; } } }


Input: Loads the web . xml file using the configured <tt > ResourceLoader< / tt > and parses the role - name elements from it using these as the set of <tt > mappableAttributes< / tt > . [CODESPLIT] public void afterPropertiesSet ( ) throws Exception { Resource webXml = resourceLoader . getResource ( "/WEB-INF/web.xml" ) ; Document doc = getDocument ( webXml . getInputStream ( ) ) ; NodeList webApp = doc . getElementsByTagName ( "web-app" ) ; if ( webApp . getLength ( ) != 1 ) { throw new IllegalArgumentException ( "Failed to find 'web-app' element in resource" + webXml ) ; } NodeList securityRoles = ( ( Element ) webApp . item ( 0 ) ) . getElementsByTagName ( "security-role" ) ; ArrayList < String > roleNames = new ArrayList <> ( ) ; for ( int i = 0 ; i < securityRoles . getLength ( ) ; i ++ ) { Element secRoleElt = ( Element ) securityRoles . item ( i ) ; NodeList roles = secRoleElt . getElementsByTagName ( "role-name" ) ; if ( roles . getLength ( ) > 0 ) { String roleName = ( ( Element ) roles . item ( 0 ) ) . getTextContent ( ) . trim ( ) ; roleNames . add ( roleName ) ; logger . info ( "Retrieved role-name '" + roleName + "' from web.xml" ) ; } else { logger . info ( "No security-role elements found in " + webXml ) ; } } mappableAttributes = Collections . unmodifiableSet ( new HashSet <> ( roleNames ) ) ; }


Input: ======================================================================================================== [CODESPLIT] public List < Sid > getSids ( Authentication authentication ) { Collection < ? extends GrantedAuthority > authorities = roleHierarchy . getReachableGrantedAuthorities ( authentication . getAuthorities ( ) ) ; List < Sid > sids = new ArrayList <> ( authorities . size ( ) + 1 ) ; sids . add ( new PrincipalSid ( authentication ) ) ; for ( GrantedAuthority authority : authorities ) { sids . add ( new GrantedAuthoritySid ( authority ) ) ; } return sids ; }


Input: Creates a TypeResolverBuilder that performs whitelisting . [CODESPLIT] private static TypeResolverBuilder < ? extends TypeResolverBuilder > createWhitelistedDefaultTyping ( ) { TypeResolverBuilder < ? extends TypeResolverBuilder > result = new WhitelistTypeResolverBuilder ( ObjectMapper . DefaultTyping . NON_FINAL ) ; result = result . init ( JsonTypeInfo . Id . CLASS , null ) ; result = result . inclusion ( JsonTypeInfo . As . PROPERTY ) ; return result ; }


Input: / * ( non - Javadoc ) [CODESPLIT] public final void onStartup ( ServletContext servletContext ) throws ServletException { beforeSpringSecurityFilterChain ( servletContext ) ; if ( this . configurationClasses != null ) { AnnotationConfigWebApplicationContext rootAppContext = new AnnotationConfigWebApplicationContext ( ) ; rootAppContext . register ( this . configurationClasses ) ; servletContext . addListener ( new ContextLoaderListener ( rootAppContext ) ) ; } if ( enableHttpSessionEventPublisher ( ) ) { servletContext . addListener ( "org.springframework.security.web.session.HttpSessionEventPublisher" ) ; } servletContext . setSessionTrackingModes ( getSessionTrackingModes ( ) ) ; insertSpringSecurityFilterChain ( servletContext ) ; afterSpringSecurityFilterChain ( servletContext ) ; }


Input: Registers the springSecurityFilterChain [CODESPLIT] private void insertSpringSecurityFilterChain ( ServletContext servletContext ) { String filterName = DEFAULT_FILTER_NAME ; DelegatingFilterProxy springSecurityFilterChain = new DelegatingFilterProxy ( filterName ) ; String contextAttribute = getWebApplicationContextAttribute ( ) ; if ( contextAttribute != null ) { springSecurityFilterChain . setContextAttribute ( contextAttribute ) ; } registerFilter ( servletContext , true , filterName , springSecurityFilterChain ) ; }


Input: Registers the provided { @link Filter } s using default generated names { @link #getSecurityDispatcherTypes () } and { @link #isAsyncSecuritySupported () } . [CODESPLIT] private void registerFilters ( ServletContext servletContext , boolean insertBeforeOtherFilters , Filter ... filters ) { Assert . notEmpty ( filters , "filters cannot be null or empty" ) ; for ( Filter filter : filters ) { if ( filter == null ) { throw new IllegalArgumentException ( "filters cannot contain null values. Got " + Arrays . asList ( filters ) ) ; } String filterName = Conventions . getVariableName ( filter ) ; registerFilter ( servletContext , insertBeforeOtherFilters , filterName , filter ) ; } }


Input: Registers the provided filter using the { @link #isAsyncSecuritySupported () } and { @link #getSecurityDispatcherTypes () } . [CODESPLIT] private final void registerFilter ( ServletContext servletContext , boolean insertBeforeOtherFilters , String filterName , Filter filter ) { Dynamic registration = servletContext . addFilter ( filterName , filter ) ; if ( registration == null ) { throw new IllegalStateException ( "Duplicate Filter registration for '" + filterName + "'. Check to ensure the Filter is only configured once." ) ; } registration . setAsyncSupported ( isAsyncSecuritySupported ( ) ) ; EnumSet < DispatcherType > dispatcherTypes = getSecurityDispatcherTypes ( ) ; registration . addMappingForUrlPatterns ( dispatcherTypes , ! insertBeforeOtherFilters , "/*" ) ; }


Input: Returns the { @link DelegatingFilterProxy#getContextAttribute () } or null if the parent { @link ApplicationContext } should be used . The default behavior is to use the parent { @link ApplicationContext } . [CODESPLIT] private String getWebApplicationContextAttribute ( ) { String dispatcherServletName = getDispatcherWebApplicationContextSuffix ( ) ; if ( dispatcherServletName == null ) { return null ; } return SERVLET_CONTEXT_PREFIX + dispatcherServletName ; }


Input: Get the { [CODESPLIT] protected EnumSet < DispatcherType > getSecurityDispatcherTypes ( ) { return EnumSet . of ( DispatcherType . REQUEST , DispatcherType . ERROR , DispatcherType . ASYNC ) ; }


Input: Loads the token data for the supplied series identifier . [CODESPLIT] public PersistentRememberMeToken getTokenForSeries ( String seriesId ) { try { return getJdbcTemplate ( ) . queryForObject ( tokensBySeriesSql , new RowMapper < PersistentRememberMeToken > ( ) { public PersistentRememberMeToken mapRow ( ResultSet rs , int rowNum ) throws SQLException { return new PersistentRememberMeToken ( rs . getString ( 1 ) , rs . getString ( 2 ) , rs . getString ( 3 ) , rs . getTimestamp ( 4 ) ) ; } } , seriesId ) ; } catch ( EmptyResultDataAccessException zeroResults ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Querying token for series '" + seriesId + "' returned no results." , zeroResults ) ; } } catch ( IncorrectResultSizeDataAccessException moreThanOne ) { logger . error ( "Querying token for series '" + seriesId + "' returned more than one value. Series" + " should be unique" ) ; } catch ( DataAccessException e ) { logger . error ( "Failed to load token for series " + seriesId , e ) ; } return null ; }


Input: Registers the public static fields of type { @link Permission } for a give class . <p > These permissions will be registered under the name of the field . See { @link BasePermission } for an example . [CODESPLIT] protected void registerPublicPermissions ( Class < ? extends Permission > clazz ) { Assert . notNull ( clazz , "Class required" ) ; Field [ ] fields = clazz . getFields ( ) ; for ( Field field : fields ) { try { Object fieldValue = field . get ( null ) ; if ( Permission . class . isAssignableFrom ( fieldValue . getClass ( ) ) ) { // Found a Permission static field Permission perm = ( Permission ) fieldValue ; String permissionName = field . getName ( ) ; registerPermission ( perm , permissionName ) ; } } catch ( Exception ignore ) { } } }


Input: Extract any <a href = https : // tools . ietf . org / html / rfc6750#section - 1 . 2 target = _blank > Bearer Token< / a > from the request and attempt an authentication . [CODESPLIT] @ Override protected void doFilterInternal ( HttpServletRequest request , HttpServletResponse response , FilterChain filterChain ) throws ServletException , IOException { final boolean debug = this . logger . isDebugEnabled ( ) ; String token ; try { token = this . bearerTokenResolver . resolve ( request ) ; } catch ( OAuth2AuthenticationException invalid ) { this . authenticationEntryPoint . commence ( request , response , invalid ) ; return ; } if ( token == null ) { filterChain . doFilter ( request , response ) ; return ; } BearerTokenAuthenticationToken authenticationRequest = new BearerTokenAuthenticationToken ( token ) ; authenticationRequest . setDetails ( this . authenticationDetailsSource . buildDetails ( request ) ) ; try { AuthenticationManager authenticationManager = this . authenticationManagerResolver . resolve ( request ) ; Authentication authenticationResult = authenticationManager . authenticate ( authenticationRequest ) ; SecurityContext context = SecurityContextHolder . createEmptyContext ( ) ; context . setAuthentication ( authenticationResult ) ; SecurityContextHolder . setContext ( context ) ; filterChain . doFilter ( request , response ) ; } catch ( AuthenticationException failed ) { SecurityContextHolder . clearContext ( ) ; if ( debug ) { this . logger . debug ( "Authentication request for failed: " + failed ) ; } this . authenticationEntryPoint . commence ( request , response , failed ) ; } }


Input: Map the given list of string attributes one - to - one to Spring Security GrantedAuthorities . [CODESPLIT] public List < GrantedAuthority > getGrantedAuthorities ( Collection < String > attributes ) { List < GrantedAuthority > result = new ArrayList <> ( attributes . size ( ) ) ; for ( String attribute : attributes ) { result . add ( getGrantedAuthority ( attribute ) ) ; } return result ; }


Input: Map the given role one - on - one to a Spring Security GrantedAuthority optionally doing case conversion and / or adding a prefix . [CODESPLIT] private GrantedAuthority getGrantedAuthority ( String attribute ) { if ( isConvertAttributeToLowerCase ( ) ) { attribute = attribute . toLowerCase ( Locale . getDefault ( ) ) ; } else if ( isConvertAttributeToUpperCase ( ) ) { attribute = attribute . toUpperCase ( Locale . getDefault ( ) ) ; } if ( isAddPrefixIfAlreadyExisting ( ) || ! attribute . startsWith ( getAttributePrefix ( ) ) ) { return new SimpleGrantedAuthority ( getAttributePrefix ( ) + attribute ) ; } else { return new SimpleGrantedAuthority ( attribute ) ; } }


Input: If available initializes the { @link DefaultLoginPageGeneratingFilter } shared object . [CODESPLIT] private void initDefaultLoginFilter ( H http ) { DefaultLoginPageGeneratingFilter loginPageGeneratingFilter = http . getSharedObject ( DefaultLoginPageGeneratingFilter . class ) ; if ( loginPageGeneratingFilter != null && ! isCustomLoginPage ( ) ) { loginPageGeneratingFilter . setFormLoginEnabled ( true ) ; loginPageGeneratingFilter . setUsernameParameter ( getUsernameParameter ( ) ) ; loginPageGeneratingFilter . setPasswordParameter ( getPasswordParameter ( ) ) ; loginPageGeneratingFilter . setLoginPageUrl ( getLoginPage ( ) ) ; loginPageGeneratingFilter . setFailureUrl ( getFailureUrl ( ) ) ; loginPageGeneratingFilter . setAuthenticationUrl ( getLoginProcessingUrl ( ) ) ; } }


Input: { [CODESPLIT] @ Override public OAuth2TokenValidatorResult validate ( Jwt token ) { Assert . notNull ( token , "token cannot be null" ) ; String tokenIssuer = token . getClaimAsString ( JwtClaimNames . ISS ) ; if ( this . issuer . equals ( tokenIssuer ) ) { return OAuth2TokenValidatorResult . success ( ) ; } else { return OAuth2TokenValidatorResult . failure ( INVALID_ISSUER ) ; } }


Input: Setting this attribute will inject the provided invalidSessionStrategy into the { [CODESPLIT] public SessionManagementConfigurer < H > invalidSessionStrategy ( InvalidSessionStrategy invalidSessionStrategy ) { Assert . notNull ( invalidSessionStrategy , "invalidSessionStrategy" ) ; this . invalidSessionStrategy = invalidSessionStrategy ; return this ; }


Input: Allows specifying the { [CODESPLIT] public SessionManagementConfigurer < H > sessionCreationPolicy ( SessionCreationPolicy sessionCreationPolicy ) { Assert . notNull ( sessionCreationPolicy , "sessionCreationPolicy cannot be null" ) ; this . sessionPolicy = sessionCreationPolicy ; return this ; }


Input: Gets the { @link InvalidSessionStrategy } to use . If null and { @link #invalidSessionUrl } is not null defaults to { @link SimpleRedirectInvalidSessionStrategy } . [CODESPLIT] InvalidSessionStrategy getInvalidSessionStrategy ( ) { if ( this . invalidSessionStrategy != null ) { return this . invalidSessionStrategy ; } if ( this . invalidSessionUrl != null ) { this . invalidSessionStrategy = new SimpleRedirectInvalidSessionStrategy ( this . invalidSessionUrl ) ; } if ( this . invalidSessionUrl == null ) { return null ; } if ( this . invalidSessionStrategy == null ) { this . invalidSessionStrategy = new SimpleRedirectInvalidSessionStrategy ( this . invalidSessionUrl ) ; } return this . invalidSessionStrategy ; }


Input: Gets the { [CODESPLIT] SessionCreationPolicy getSessionCreationPolicy ( ) { if ( this . sessionPolicy != null ) { return this . sessionPolicy ; } SessionCreationPolicy sessionPolicy = getBuilder ( ) . getSharedObject ( SessionCreationPolicy . class ) ; return sessionPolicy == null ? SessionCreationPolicy . IF_REQUIRED : sessionPolicy ; }


Input: Returns true if the { [CODESPLIT] private boolean isAllowSessionCreation ( ) { SessionCreationPolicy sessionPolicy = getSessionCreationPolicy ( ) ; return SessionCreationPolicy . ALWAYS == sessionPolicy || SessionCreationPolicy . IF_REQUIRED == sessionPolicy ; }


Input: Gets the customized { @link SessionAuthenticationStrategy } if { @link #sessionAuthenticationStrategy ( SessionAuthenticationStrategy ) } was specified . Otherwise creates a default { @link SessionAuthenticationStrategy } . [CODESPLIT] private SessionAuthenticationStrategy getSessionAuthenticationStrategy ( H http ) { if ( this . sessionAuthenticationStrategy != null ) { return this . sessionAuthenticationStrategy ; } List < SessionAuthenticationStrategy > delegateStrategies = this . sessionAuthenticationStrategies ; SessionAuthenticationStrategy defaultSessionAuthenticationStrategy ; if ( this . providedSessionAuthenticationStrategy == null ) { // If the user did not provide a SessionAuthenticationStrategy // then default to sessionFixationAuthenticationStrategy defaultSessionAuthenticationStrategy = postProcess ( this . sessionFixationAuthenticationStrategy ) ; } else { defaultSessionAuthenticationStrategy = this . providedSessionAuthenticationStrategy ; } if ( isConcurrentSessionControlEnabled ( ) ) { SessionRegistry sessionRegistry = getSessionRegistry ( http ) ; ConcurrentSessionControlAuthenticationStrategy concurrentSessionControlStrategy = new ConcurrentSessionControlAuthenticationStrategy ( sessionRegistry ) ; concurrentSessionControlStrategy . setMaximumSessions ( this . maximumSessions ) ; concurrentSessionControlStrategy . setExceptionIfMaximumExceeded ( this . maxSessionsPreventsLogin ) ; concurrentSessionControlStrategy = postProcess ( concurrentSessionControlStrategy ) ; RegisterSessionAuthenticationStrategy registerSessionStrategy = new RegisterSessionAuthenticationStrategy ( sessionRegistry ) ; registerSessionStrategy = postProcess ( registerSessionStrategy ) ; delegateStrategies . addAll ( Arrays . asList ( concurrentSessionControlStrategy , defaultSessionAuthenticationStrategy , registerSessionStrategy ) ) ; } else { delegateStrategies . add ( defaultSessionAuthenticationStrategy ) ; } this . sessionAuthenticationStrategy = postProcess ( new CompositeSessionAuthenticationStrategy ( delegateStrategies ) ) ; return this . sessionAuthenticationStrategy ; }


Input: ======================================================================================================== [CODESPLIT] public void afterPropertiesSet ( ) throws Exception { Assert . hasLength ( this . service , "service cannot be empty." ) ; Assert . hasLength ( this . artifactParameter , "artifactParameter cannot be empty." ) ; Assert . hasLength ( this . serviceParameter , "serviceParameter cannot be empty." ) ; }


Input: Invokes the { [CODESPLIT] public void doFilter ( ServletRequest req , ServletResponse res , FilterChain chain ) throws IOException , ServletException { HttpServletRequest request = ( HttpServletRequest ) req ; HttpServletResponse response = ( HttpServletResponse ) res ; if ( ! requiresAuthentication ( request , response ) ) { chain . doFilter ( request , response ) ; return ; } if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Request is to process authentication" ) ; } Authentication authResult ; try { authResult = attemptAuthentication ( request , response ) ; if ( authResult == null ) { // return immediately as subclass has indicated that it hasn't completed // authentication return ; } sessionStrategy . onAuthentication ( authResult , request , response ) ; } catch ( InternalAuthenticationServiceException failed ) { logger . error ( "An internal error occurred while trying to authenticate the user." , failed ) ; unsuccessfulAuthentication ( request , response , failed ) ; return ; } catch ( AuthenticationException failed ) { // Authentication failed unsuccessfulAuthentication ( request , response , failed ) ; return ; } // Authentication success if ( continueChainBeforeSuccessfulAuthentication ) { chain . doFilter ( request , response ) ; } successfulAuthentication ( request , response , chain , authResult ) ; }


Input: Default behaviour for successful authentication . <ol > <li > Sets the successful <tt > Authentication< / tt > object on the { @link SecurityContextHolder } < / li > <li > Informs the configured <tt > RememberMeServices< / tt > of the successful login< / li > <li > Fires an { @link InteractiveAuthenticationSuccessEvent } via the configured <tt > ApplicationEventPublisher< / tt > < / li > <li > Delegates additional behaviour to the { @link AuthenticationSuccessHandler } . < / li > < / ol > [CODESPLIT] protected void successfulAuthentication ( HttpServletRequest request , HttpServletResponse response , FilterChain chain , Authentication authResult ) throws IOException , ServletException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Authentication success. Updating SecurityContextHolder to contain: " + authResult ) ; } SecurityContextHolder . getContext ( ) . setAuthentication ( authResult ) ; rememberMeServices . loginSuccess ( request , response , authResult ) ; // Fire event if ( this . eventPublisher != null ) { eventPublisher . publishEvent ( new InteractiveAuthenticationSuccessEvent ( authResult , this . getClass ( ) ) ) ; } successHandler . onAuthenticationSuccess ( request , response , authResult ) ; }


Input: Default behaviour for unsuccessful authentication . <ol > <li > Clears the { [CODESPLIT] protected void unsuccessfulAuthentication ( HttpServletRequest request , HttpServletResponse response , AuthenticationException failed ) throws IOException , ServletException { SecurityContextHolder . clearContext ( ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Authentication request failed: " + failed . toString ( ) , failed ) ; logger . debug ( "Updated SecurityContextHolder to contain null Authentication" ) ; logger . debug ( "Delegating to authentication failure handler " + failureHandler ) ; } rememberMeServices . loginFail ( request , response ) ; failureHandler . onAuthenticationFailure ( request , response , failed ) ; }


Input: Populate the AccessDeniedHandler on the { @link CsrfFilter } [CODESPLIT] void initAccessDeniedHandler ( BeanDefinition invalidSessionStrategy , BeanMetadataElement defaultDeniedHandler ) { BeanMetadataElement accessDeniedHandler = createAccessDeniedHandler ( invalidSessionStrategy , defaultDeniedHandler ) ; this . csrfFilter . getPropertyValues ( ) . addPropertyValue ( "accessDeniedHandler" , accessDeniedHandler ) ; }


Input: Creates the { @link AccessDeniedHandler } from the result of { @link #getDefaultAccessDeniedHandler ( HttpSecurityBuilder ) } and { @link #getInvalidSessionStrategy ( HttpSecurityBuilder ) } . If { @link #getInvalidSessionStrategy ( HttpSecurityBuilder ) } is non - null then a { @link DelegatingAccessDeniedHandler } is used in combination with { @link InvalidSessionAccessDeniedHandler } and the { @link #getDefaultAccessDeniedHandler ( HttpSecurityBuilder ) } . Otherwise only { @link #getDefaultAccessDeniedHandler ( HttpSecurityBuilder ) } is used . [CODESPLIT] private BeanMetadataElement createAccessDeniedHandler ( BeanDefinition invalidSessionStrategy , BeanMetadataElement defaultDeniedHandler ) { if ( invalidSessionStrategy == null ) { return defaultDeniedHandler ; } ManagedMap < Class < ? extends AccessDeniedException > , BeanDefinition > handlers = new ManagedMap < Class < ? extends AccessDeniedException > , BeanDefinition > ( ) ; BeanDefinitionBuilder invalidSessionHandlerBldr = BeanDefinitionBuilder . rootBeanDefinition ( InvalidSessionAccessDeniedHandler . class ) ; invalidSessionHandlerBldr . addConstructorArgValue ( invalidSessionStrategy ) ; handlers . put ( MissingCsrfTokenException . class , invalidSessionHandlerBldr . getBeanDefinition ( ) ) ; BeanDefinitionBuilder deniedBldr = BeanDefinitionBuilder . rootBeanDefinition ( DelegatingAccessDeniedHandler . class ) ; deniedBldr . addConstructorArgValue ( handlers ) ; deniedBldr . addConstructorArgValue ( defaultDeniedHandler ) ; return deniedBldr . getBeanDefinition ( ) ; }


Input: Generates a SecretKey . [CODESPLIT] public static SecretKey newSecretKey ( String algorithm , String password ) { return newSecretKey ( algorithm , new PBEKeySpec ( password . toCharArray ( ) ) ) ; }


Input: Generates a SecretKey . [CODESPLIT] public static SecretKey newSecretKey ( String algorithm , PBEKeySpec keySpec ) { try { SecretKeyFactory factory = SecretKeyFactory . getInstance ( algorithm ) ; return factory . generateSecret ( keySpec ) ; } catch ( NoSuchAlgorithmException e ) { throw new IllegalArgumentException ( "Not a valid encryption algorithm" , e ) ; } catch ( InvalidKeySpecException e ) { throw new IllegalArgumentException ( "Not a valid secret key" , e ) ; } }


Input: Constructs a new Cipher . [CODESPLIT] public static Cipher newCipher ( String algorithm ) { try { return Cipher . getInstance ( algorithm ) ; } catch ( NoSuchAlgorithmException e ) { throw new IllegalArgumentException ( "Not a valid encryption algorithm" , e ) ; } catch ( NoSuchPaddingException e ) { throw new IllegalStateException ( "Should not happen" , e ) ; } }


Input: Initializes the Cipher for use . [CODESPLIT] public static < T extends AlgorithmParameterSpec > T getParameterSpec ( Cipher cipher , Class < T > parameterSpecClass ) { try { return cipher . getParameters ( ) . getParameterSpec ( parameterSpecClass ) ; } catch ( InvalidParameterSpecException e ) { throw new IllegalArgumentException ( "Unable to access parameter" , e ) ; } }


Input: Initializes the Cipher for use . [CODESPLIT] public static void initCipher ( Cipher cipher , int mode , SecretKey secretKey ) { initCipher ( cipher , mode , secretKey , null ) ; }


Input: Initializes the Cipher for use . [CODESPLIT] public static void initCipher ( Cipher cipher , int mode , SecretKey secretKey , byte [ ] salt , int iterationCount ) { initCipher ( cipher , mode , secretKey , new PBEParameterSpec ( salt , iterationCount ) ) ; }


Input: Initializes the Cipher for use . [CODESPLIT] public static void initCipher ( Cipher cipher , int mode , SecretKey secretKey , AlgorithmParameterSpec parameterSpec ) { try { if ( parameterSpec != null ) { cipher . init ( mode , secretKey , parameterSpec ) ; } else { cipher . init ( mode , secretKey ) ; } } catch ( InvalidKeyException e ) { throw new IllegalArgumentException ( "Unable to initialize due to invalid secret key" , e ) ; } catch ( InvalidAlgorithmParameterException e ) { throw new IllegalStateException ( "Unable to initialize due to invalid decryption parameter spec" , e ) ; } }


Input: Invokes the Cipher to perform encryption or decryption ( depending on the initialized mode ) . [CODESPLIT] public static byte [ ] doFinal ( Cipher cipher , byte [ ] input ) { try { return cipher . doFinal ( input ) ; } catch ( IllegalBlockSizeException e ) { throw new IllegalStateException ( "Unable to invoke Cipher due to illegal block size" , e ) ; } catch ( BadPaddingException e ) { throw new IllegalStateException ( "Unable to invoke Cipher due to bad padding" , e ) ; } }


Input: Check whether all required properties have been set . [CODESPLIT] @ Override public void afterPropertiesSet ( ) { try { super . afterPropertiesSet ( ) ; } catch ( ServletException e ) { // convert to RuntimeException for passivity on afterPropertiesSet signature throw new RuntimeException ( e ) ; } Assert . notNull ( authenticationManager , "An AuthenticationManager must be set" ) ; }


Input: Try to authenticate a pre - authenticated user with Spring Security if the user has not yet been authenticated . [CODESPLIT] public void doFilter ( ServletRequest request , ServletResponse response , FilterChain chain ) throws IOException , ServletException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Checking secure context token: " + SecurityContextHolder . getContext ( ) . getAuthentication ( ) ) ; } if ( requiresAuthentication ( ( HttpServletRequest ) request ) ) { doAuthenticate ( ( HttpServletRequest ) request , ( HttpServletResponse ) response ) ; } chain . doFilter ( request , response ) ; }


Input: Determines if the current principal has changed . The default implementation tries [CODESPLIT] protected boolean principalChanged ( HttpServletRequest request , Authentication currentAuthentication ) { Object principal = getPreAuthenticatedPrincipal ( request ) ; if ( ( principal instanceof String ) && currentAuthentication . getName ( ) . equals ( principal ) ) { return false ; } if ( principal != null && principal . equals ( currentAuthentication . getPrincipal ( ) ) ) { return false ; } if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Pre-authenticated principal has changed to " + principal + " and will be reauthenticated" ) ; } return true ; }


Input: Do the actual authentication for a pre - authenticated user . [CODESPLIT] private void doAuthenticate ( HttpServletRequest request , HttpServletResponse response ) throws IOException , ServletException { Authentication authResult ; Object principal = getPreAuthenticatedPrincipal ( request ) ; Object credentials = getPreAuthenticatedCredentials ( request ) ; if ( principal == null ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "No pre-authenticated principal found in request" ) ; } return ; } if ( logger . isDebugEnabled ( ) ) { logger . debug ( "preAuthenticatedPrincipal = " + principal + ", trying to authenticate" ) ; } try { PreAuthenticatedAuthenticationToken authRequest = new PreAuthenticatedAuthenticationToken ( principal , credentials ) ; authRequest . setDetails ( authenticationDetailsSource . buildDetails ( request ) ) ; authResult = authenticationManager . authenticate ( authRequest ) ; successfulAuthentication ( request , response , authResult ) ; } catch ( AuthenticationException failed ) { unsuccessfulAuthentication ( request , response , failed ) ; if ( ! continueFilterChainOnUnsuccessfulAuthentication ) { throw failed ; } } }


Input: Puts the <code > Authentication< / code > instance returned by the authentication manager into the secure context . [CODESPLIT] protected void successfulAuthentication ( HttpServletRequest request , HttpServletResponse response , Authentication authResult ) throws IOException , ServletException { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Authentication success: " + authResult ) ; } SecurityContextHolder . getContext ( ) . setAuthentication ( authResult ) ; // Fire event if ( this . eventPublisher != null ) { eventPublisher . publishEvent ( new InteractiveAuthenticationSuccessEvent ( authResult , this . getClass ( ) ) ) ; } if ( authenticationSuccessHandler != null ) { authenticationSuccessHandler . onAuthenticationSuccess ( request , response , authResult ) ; } }


Input: Ensures the authentication object in the secure context is set to null when authentication fails . <p > Caches the failure exception as a request attribute [CODESPLIT] protected void unsuccessfulAuthentication ( HttpServletRequest request , HttpServletResponse response , AuthenticationException failed ) throws IOException , ServletException { SecurityContextHolder . clearContext ( ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Cleared security context due to exception" , failed ) ; } request . setAttribute ( WebAttributes . AUTHENTICATION_EXCEPTION , failed ) ; if ( authenticationFailureHandler != null ) { authenticationFailureHandler . onAuthenticationFailure ( request , response , failed ) ; } }


Input: Makes sure { [CODESPLIT] @ Override public final void sendError ( int sc , String msg ) throws IOException { doOnResponseCommitted ( ) ; super . sendError ( sc , msg ) ; }


Input: Adds the contentLengthToWrite to the total contentWritten size and checks to see if the response should be written . [CODESPLIT] private void checkContentLength ( long contentLengthToWrite ) { this . contentWritten += contentLengthToWrite ; boolean isBodyFullyWritten = this . contentLength > 0 && this . contentWritten >= this . contentLength ; int bufferSize = getBufferSize ( ) ; boolean requiresFlush = bufferSize > 0 && this . contentWritten >= bufferSize ; if ( isBodyFullyWritten || requiresFlush ) { doOnResponseCommitted ( ) ; } }


Input: Delay the lookup of the { @link ExpressionParser } to prevent SEC - 2136 [CODESPLIT] private ExpressionParser getParser ( ) { if ( this . parser != null ) { return this . parser ; } synchronized ( parserLock ) { this . parser = handler . getExpressionParser ( ) ; this . handler = null ; } return this . parser ; }


Input: <p > Determines which HTTP methods should be allowed . The default is to allow DELETE GET HEAD OPTIONS PATCH POST and PUT . < / p > [CODESPLIT] public void setAllowedHttpMethods ( Collection < String > allowedHttpMethods ) { if ( allowedHttpMethods == null ) { throw new IllegalArgumentException ( "allowedHttpMethods cannot be null" ) ; } if ( allowedHttpMethods == ALLOW_ANY_HTTP_METHOD ) { this . allowedHttpMethods = ALLOW_ANY_HTTP_METHOD ; } else { this . allowedHttpMethods = new HashSet <> ( allowedHttpMethods ) ; } }


Input: <p > Determines if a percent % that is URL encoded %25 should be allowed in the path or not . The default is not to allow this behavior because it is a frequent source of security exploits . < / p > <p > For example this can lead to exploits that involve double URL encoding that lead to bypassing security constraints . < / p > [CODESPLIT] public void setAllowUrlEncodedPercent ( boolean allowUrlEncodedPercent ) { if ( allowUrlEncodedPercent ) { this . encodedUrlBlacklist . remove ( ENCODED_PERCENT ) ; this . decodedUrlBlacklist . remove ( PERCENT ) ; } else { this . encodedUrlBlacklist . add ( ENCODED_PERCENT ) ; this . decodedUrlBlacklist . add ( PERCENT ) ; } }


Input: Creates a mapping of the supplied authorities based on the case - conversion and prefix settings . The mapping will be one - to - one unless duplicates are produced during the conversion . If a default authority has been set this will also be assigned to each mapping . [CODESPLIT] public Set < GrantedAuthority > mapAuthorities ( Collection < ? extends GrantedAuthority > authorities ) { HashSet < GrantedAuthority > mapped = new HashSet <> ( authorities . size ( ) ) ; for ( GrantedAuthority authority : authorities ) { mapped . add ( mapAuthority ( authority . getAuthority ( ) ) ) ; } if ( defaultAuthority != null ) { mapped . add ( defaultAuthority ) ; } return mapped ; }


Input: Specifies where users will go after authenticating successfully if they have not visited a secured page prior to authenticating or { @code alwaysUse } is true . This is a shortcut for calling { @link #successHandler ( AuthenticationSuccessHandler ) } . [CODESPLIT] public final T defaultSuccessUrl ( String defaultSuccessUrl , boolean alwaysUse ) { SavedRequestAwareAuthenticationSuccessHandler handler = new SavedRequestAwareAuthenticationSuccessHandler ( ) ; handler . setDefaultTargetUrl ( defaultSuccessUrl ) ; handler . setAlwaysUseDefaultTargetUrl ( alwaysUse ) ; this . defaultSuccessHandler = handler ; return successHandler ( handler ) ; }


Input: Specifies the URL to validate the credentials . [CODESPLIT] public T loginProcessingUrl ( String loginProcessingUrl ) { this . loginProcessingUrl = loginProcessingUrl ; authFilter . setRequiresAuthenticationRequestMatcher ( createLoginProcessingUrlMatcher ( loginProcessingUrl ) ) ; return getSelf ( ) ; }


Input: The URL to send users if authentication fails . This is a shortcut for invoking { @link #failureHandler ( AuthenticationFailureHandler ) } . The default is / login?error . [CODESPLIT] public final T failureUrl ( String authenticationFailureUrl ) { T result = failureHandler ( new SimpleUrlAuthenticationFailureHandler ( authenticationFailureUrl ) ) ; this . failureUrl = authenticationFailureUrl ; return result ; }


Input: <p > Specifies the URL to send users to if login is required . If used with { @link WebSecurityConfigurerAdapter } a default login page will be generated when this attribute is not specified . < / p > [CODESPLIT] protected T loginPage ( String loginPage ) { setLoginPage ( loginPage ) ; updateAuthenticationDefaults ( ) ; this . customLoginPage = true ; return getSelf ( ) ; }


Input: Updates the default values for authentication . [CODESPLIT] protected final void updateAuthenticationDefaults ( ) { if ( loginProcessingUrl == null ) { loginProcessingUrl ( loginPage ) ; } if ( failureHandler == null ) { failureUrl ( loginPage + "?error" ) ; } final LogoutConfigurer < B > logoutConfigurer = getBuilder ( ) . getConfigurer ( LogoutConfigurer . class ) ; if ( logoutConfigurer != null && ! logoutConfigurer . isCustomLogoutSuccess ( ) ) { logoutConfigurer . logoutSuccessUrl ( loginPage + "?logout" ) ; } }


Input: Updates the default values for access . [CODESPLIT] protected final void updateAccessDefaults ( B http ) { if ( permitAll ) { PermitAllSupport . permitAll ( http , loginPage , loginProcessingUrl , failureUrl ) ; } }


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


Input: Sets the repository for authorized client ( s ) . [CODESPLIT] public OAuth2LoginConfigurer < B > authorizedClientRepository ( OAuth2AuthorizedClientRepository authorizedClientRepository ) { Assert . notNull ( authorizedClientRepository , "authorizedClientRepository cannot be null" ) ; this . getBuilder ( ) . setSharedObject ( OAuth2AuthorizedClientRepository . class , authorizedClientRepository ) ; return this ; }


Input: Sets the service for authorized client ( s ) . [CODESPLIT] public OAuth2LoginConfigurer < B > authorizedClientService ( OAuth2AuthorizedClientService authorizedClientService ) { Assert . notNull ( authorizedClientService , "authorizedClientService cannot be null" ) ; this . authorizedClientRepository ( new AuthenticatedPrincipalOAuth2AuthorizedClientRepository ( authorizedClientService ) ) ; return this ; }


Input: Allows registering multiple { @link RequestMatcher } instances to a collection of { @link ConfigAttribute } instances [CODESPLIT] private void interceptUrl ( Iterable < ? extends RequestMatcher > requestMatchers , Collection < ConfigAttribute > configAttributes ) { for ( RequestMatcher requestMatcher : requestMatchers ) { REGISTRY . addMapping ( new AbstractConfigAttributeRequestMatcherRegistry . UrlMapping ( requestMatcher , configAttributes ) ) ; } }


Input: { [CODESPLIT] @ Override public OAuth2TokenValidatorResult validate ( Jwt jwt ) { Assert . notNull ( jwt , "jwt cannot be null" ) ; Instant expiry = jwt . getExpiresAt ( ) ; if ( expiry != null ) { if ( Instant . now ( this . clock ) . minus ( clockSkew ) . isAfter ( expiry ) ) { OAuth2Error error = new OAuth2Error ( OAuth2ErrorCodes . INVALID_REQUEST , String . format ( "Jwt expired at %s" , jwt . getExpiresAt ( ) ) , "https://tools.ietf.org/html/rfc6750#section-3.1" ) ; return OAuth2TokenValidatorResult . failure ( error ) ; } } Instant notBefore = jwt . getNotBefore ( ) ; if ( notBefore != null ) { if ( Instant . now ( this . clock ) . plus ( clockSkew ) . isBefore ( notBefore ) ) { OAuth2Error error = new OAuth2Error ( OAuth2ErrorCodes . INVALID_REQUEST , String . format ( "Jwt used before %s" , jwt . getNotBefore ( ) ) , "https://tools.ietf.org/html/rfc6750#section-3.1" ) ; return OAuth2TokenValidatorResult . failure ( error ) ; } } return OAuth2TokenValidatorResult . success ( ) ; }


Input: Register escalate and configure the AspectJ auto proxy creator based on the value of the [CODESPLIT] public void registerBeanDefinitions ( AnnotationMetadata importingClassMetadata , BeanDefinitionRegistry registry ) { BeanDefinition interceptor = registry . getBeanDefinition ( "methodSecurityInterceptor" ) ; BeanDefinitionBuilder aspect = BeanDefinitionBuilder . rootBeanDefinition ( "org.springframework.security.access.intercept.aspectj.aspect.AnnotationSecurityAspect" ) ; aspect . setFactoryMethod ( "aspectOf" ) ; aspect . setRole ( BeanDefinition . ROLE_INFRASTRUCTURE ) ; aspect . addPropertyValue ( "securityInterceptor" , interceptor ) ; registry . registerBeanDefinition ( "annotationSecurityAspect$0" , aspect . getBeanDefinition ( ) ) ; }


Input: ======================================================================================================== [CODESPLIT] @ Override public UserDetails mapUserFromContext ( DirContextOperations ctx , String username , Collection < ? extends GrantedAuthority > authorities ) { String dn = ctx . getNameInNamespace ( ) ; this . logger . debug ( "Mapping user details from context with DN: " + dn ) ; LdapUserDetailsImpl . Essence essence = new LdapUserDetailsImpl . Essence ( ) ; essence . setDn ( dn ) ; Object passwordValue = ctx . getObjectAttribute ( this . passwordAttributeName ) ; if ( passwordValue != null ) { essence . setPassword ( mapPassword ( passwordValue ) ) ; } essence . setUsername ( username ) ; // Map the roles for ( int i = 0 ; ( this . roleAttributes != null ) && ( i < this . roleAttributes . length ) ; i ++ ) { String [ ] rolesForAttribute = ctx . getStringAttributes ( this . roleAttributes [ i ] ) ; if ( rolesForAttribute == null ) { this . logger . debug ( "Couldn't read role attribute '" + this . roleAttributes [ i ] + "' for user " + dn ) ; continue ; } for ( String role : rolesForAttribute ) { GrantedAuthority authority = createAuthority ( role ) ; if ( authority != null ) { essence . addAuthority ( authority ) ; } } } // Add the supplied authorities for ( GrantedAuthority authority : authorities ) { essence . addAuthority ( authority ) ; } // Check for PPolicy data PasswordPolicyResponseControl ppolicy = ( PasswordPolicyResponseControl ) ctx . getObjectAttribute ( PasswordPolicyControl . OID ) ; if ( ppolicy != null ) { essence . setTimeBeforeExpiration ( ppolicy . getTimeBeforeExpiration ( ) ) ; essence . setGraceLoginsRemaining ( ppolicy . getGraceLoginsRemaining ( ) ) ; } return essence . createUserDetails ( ) ; }


Input: Extension point to allow customized creation of the user s password from the attribute stored in the directory . [CODESPLIT] protected String mapPassword ( Object passwordValue ) { if ( ! ( passwordValue instanceof String ) ) { // Assume it's binary passwordValue = new String ( ( byte [ ] ) passwordValue ) ; } return ( String ) passwordValue ; }


Input: Creates a GrantedAuthority from a role attribute . Override to customize authority object creation . <p > The default implementation converts string attributes to roles making use of the <tt > rolePrefix< / tt > and <tt > convertToUpperCase< / tt > properties . Non - String attributes are ignored . < / p > [CODESPLIT] protected GrantedAuthority createAuthority ( Object role ) { if ( role instanceof String ) { if ( this . convertToUpperCase ) { role = ( ( String ) role ) . toUpperCase ( ) ; } return new SimpleGrantedAuthority ( this . rolePrefix + role ) ; } return null ; }


Input: Use this { @link Jwt } Validator [CODESPLIT] public void setJwtValidator ( OAuth2TokenValidator < Jwt > jwtValidator ) { Assert . notNull ( jwtValidator , "jwtValidator cannot be null" ) ; this . jwtValidator = jwtValidator ; this . delegate . setJwtValidator ( jwtValidator ) ; }


Input: Sets the { @link RestOperations } used when requesting the JSON Web Key ( JWK ) Set . [CODESPLIT] public final void setRestOperations ( RestOperations restOperations ) { Assert . notNull ( restOperations , "restOperations cannot be null" ) ; this . jwtDecoderBuilder = this . jwtDecoderBuilder . restOperations ( restOperations ) ; this . delegate = makeDelegate ( ) ; }


Input: resolve the argument to inject into the controller parameter . @param parameter the method parameter . @param mavContainer the model and view container . @param webRequest the web request . @param binderFactory the web data binder factory . [CODESPLIT] public Object resolveArgument ( MethodParameter parameter , ModelAndViewContainer mavContainer , NativeWebRequest webRequest , WebDataBinderFactory binderFactory ) throws Exception { SecurityContext securityContext = SecurityContextHolder . getContext ( ) ; if ( securityContext == null ) { return null ; } Object securityContextResult = securityContext ; CurrentSecurityContext securityContextAnnotation = findMethodAnnotation ( CurrentSecurityContext . class , parameter ) ; String expressionToParse = securityContextAnnotation . expression ( ) ; if ( StringUtils . hasLength ( expressionToParse ) ) { StandardEvaluationContext context = new StandardEvaluationContext ( ) ; context . setRootObject ( securityContext ) ; context . setVariable ( "this" , securityContext ) ; Expression expression = this . parser . parseExpression ( expressionToParse ) ; securityContextResult = expression . getValue ( context ) ; } if ( securityContextResult != null && ! parameter . getParameterType ( ) . isAssignableFrom ( securityContextResult . getClass ( ) ) ) { if ( securityContextAnnotation . errorOnInvalidType ( ) ) { throw new ClassCastException ( securityContextResult + " is not assignable to " + parameter . getParameterType ( ) ) ; } else { return null ; } } return securityContextResult ; }


Input: Obtains the specified { @link Annotation } on the specified { @link MethodParameter } . [CODESPLIT] private < T extends Annotation > T findMethodAnnotation ( Class < T > annotationClass , MethodParameter parameter ) { T annotation = parameter . getParameterAnnotation ( annotationClass ) ; if ( annotation != null ) { return annotation ; } Annotation [ ] annotationsToSearch = parameter . getParameterAnnotations ( ) ; for ( Annotation toSearch : annotationsToSearch ) { annotation = AnnotationUtils . findAnnotation ( toSearch . annotationType ( ) , annotationClass ) ; if ( annotation != null ) { return annotation ; } } return null ; }


Input: / * ( non - Javadoc ) [CODESPLIT] public Object resolveArgument ( MethodParameter parameter , ModelAndViewContainer mavContainer , NativeWebRequest webRequest , WebDataBinderFactory binderFactory ) 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 ) ; context . setBeanResolver ( beanResolver ) ; 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: <p > Create a { [CODESPLIT] public static OAuth2TokenValidator < Jwt > createDefaultWithIssuer ( String issuer ) { List < OAuth2TokenValidator < Jwt >> validators = new ArrayList <> ( ) ; validators . add ( new JwtTimestampValidator ( ) ) ; validators . add ( new JwtIssuerValidator ( issuer ) ) ; return new DelegatingOAuth2TokenValidator <> ( validators ) ; }