Input: { [CODESPLIT] @ Override public void postProcessBeanFactory ( ConfigurableListableBeanFactory beanFactory ) throws BeansException { if ( hasUserDefinedConversionService ( beanFactory ) ) { return ; } Converter < String , RSAPrivateKey > pkcs8 = pkcs8 ( ) ; Converter < String , RSAPublicKey > x509 = x509 ( ) ; ConversionService service = beanFactory . getConversionService ( ) ; if ( service instanceof ConverterRegistry ) { ConverterRegistry registry = ( ConverterRegistry ) service ; registry . addConverter ( String . class , RSAPrivateKey . class , pkcs8 ) ; registry . addConverter ( String . class , RSAPublicKey . class , x509 ) ; } else { beanFactory . addPropertyEditorRegistrar ( registry -> { registry . registerCustomEditor ( RSAPublicKey . class , new ConverterPropertyEditorAdapter <> ( x509 ) ) ; registry . registerCustomEditor ( RSAPrivateKey . class , new ConverterPropertyEditorAdapter <> ( pkcs8 ) ) ; } ) ; } }


Input: Template implementation which locates the Spring Security cookie decodes it into a delimited array of tokens and submits it to subclasses for processing via the <tt > processAutoLoginCookie< / tt > method . <p > The returned username is then used to load the UserDetails object for the user which in turn is used to create a valid authentication token . [CODESPLIT] @ Override public final Authentication autoLogin ( HttpServletRequest request , HttpServletResponse response ) { String rememberMeCookie = extractRememberMeCookie ( request ) ; if ( rememberMeCookie == null ) { return null ; } logger . debug ( "Remember-me cookie detected" ) ; if ( rememberMeCookie . length ( ) == 0 ) { logger . debug ( "Cookie was empty" ) ; cancelCookie ( request , response ) ; return null ; } UserDetails user = null ; try { String [ ] cookieTokens = decodeCookie ( rememberMeCookie ) ; user = processAutoLoginCookie ( cookieTokens , request , response ) ; userDetailsChecker . check ( user ) ; logger . debug ( "Remember-me cookie accepted" ) ; return createSuccessfulAuthentication ( request , user ) ; } catch ( CookieTheftException cte ) { cancelCookie ( request , response ) ; throw cte ; } catch ( UsernameNotFoundException noUser ) { logger . debug ( "Remember-me login was valid but corresponding user not found." , noUser ) ; } catch ( InvalidCookieException invalidCookie ) { logger . debug ( "Invalid remember-me cookie: " + invalidCookie . getMessage ( ) ) ; } catch ( AccountStatusException statusInvalid ) { logger . debug ( "Invalid UserDetails: " + statusInvalid . getMessage ( ) ) ; } catch ( RememberMeAuthenticationException e ) { logger . debug ( e . getMessage ( ) ) ; } cancelCookie ( request , response ) ; return null ; }


Input: Locates the Spring Security remember me cookie in the request and returns its value . The cookie is searched for by name and also by matching the context path to the cookie path . [CODESPLIT] protected String extractRememberMeCookie ( HttpServletRequest request ) { Cookie [ ] cookies = request . getCookies ( ) ; if ( ( cookies == null ) || ( cookies . length == 0 ) ) { return null ; } for ( Cookie cookie : cookies ) { if ( cookieName . equals ( cookie . getName ( ) ) ) { return cookie . getValue ( ) ; } } return null ; }


Input: Creates the final <tt > Authentication< / tt > object returned from the <tt > autoLogin< / tt > method . <p > By default it will create a <tt > RememberMeAuthenticationToken< / tt > instance . [CODESPLIT] protected Authentication createSuccessfulAuthentication ( HttpServletRequest request , UserDetails user ) { RememberMeAuthenticationToken auth = new RememberMeAuthenticationToken ( key , user , authoritiesMapper . mapAuthorities ( user . getAuthorities ( ) ) ) ; auth . setDetails ( authenticationDetailsSource . buildDetails ( request ) ) ; return auth ; }


Input: Decodes the cookie and splits it into a set of token strings using the : delimiter . [CODESPLIT] protected String [ ] decodeCookie ( String cookieValue ) throws InvalidCookieException { for ( int j = 0 ; j < cookieValue . length ( ) % 4 ; j ++ ) { cookieValue = cookieValue + "=" ; } try { Base64 . getDecoder ( ) . decode ( cookieValue . getBytes ( ) ) ; } catch ( IllegalArgumentException e ) { throw new InvalidCookieException ( "Cookie token was not Base64 encoded; value was '" + cookieValue + "'" ) ; } String cookieAsPlainText = new String ( Base64 . getDecoder ( ) . decode ( cookieValue . getBytes ( ) ) ) ; String [ ] tokens = StringUtils . delimitedListToStringArray ( cookieAsPlainText , DELIMITER ) ; for ( int i = 0 ; i < tokens . length ; i ++ ) { try { tokens [ i ] = URLDecoder . decode ( tokens [ i ] , StandardCharsets . UTF_8 . toString ( ) ) ; } catch ( UnsupportedEncodingException e ) { logger . error ( e . getMessage ( ) , e ) ; } } return tokens ; }


Input: Inverse operation of decodeCookie . [CODESPLIT] protected String encodeCookie ( String [ ] cookieTokens ) { StringBuilder sb = new StringBuilder ( ) ; for ( int i = 0 ; i < cookieTokens . length ; i ++ ) { try { sb . append ( URLEncoder . encode ( cookieTokens [ i ] , StandardCharsets . UTF_8 . toString ( ) ) ) ; } catch ( UnsupportedEncodingException e ) { logger . error ( e . getMessage ( ) , e ) ; } if ( i < cookieTokens . length - 1 ) { sb . append ( DELIMITER ) ; } } String value = sb . toString ( ) ; sb = new StringBuilder ( new String ( Base64 . getEncoder ( ) . encode ( value . getBytes ( ) ) ) ) ; while ( sb . charAt ( sb . length ( ) - 1 ) == ' ' ) { sb . deleteCharAt ( sb . length ( ) - 1 ) ; } return sb . toString ( ) ; }


Input: { @inheritDoc } [CODESPLIT] @ Override public final void loginSuccess ( HttpServletRequest request , HttpServletResponse response , Authentication successfulAuthentication ) { if ( ! rememberMeRequested ( request , parameter ) ) { logger . debug ( "Remember-me login not requested." ) ; return ; } onLoginSuccess ( request , response , successfulAuthentication ) ; }


Input: Allows customization of whether a remember - me login has been requested . The default is to return true if <tt > alwaysRemember< / tt > is set or the configured parameter name has been included in the request and is set to the value true . [CODESPLIT] protected boolean rememberMeRequested ( HttpServletRequest request , String parameter ) { if ( alwaysRemember ) { return true ; } String paramValue = request . getParameter ( parameter ) ; if ( paramValue != null ) { if ( paramValue . equalsIgnoreCase ( "true" ) || paramValue . equalsIgnoreCase ( "on" ) || paramValue . equalsIgnoreCase ( "yes" ) || paramValue . equals ( "1" ) ) { return true ; } } if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Did not send remember-me cookie (principal did not set parameter '" + parameter + "')" ) ; } return false ; }


Input: Sets a cancel cookie ( with maxAge = 0 ) on the response to disable persistent logins . [CODESPLIT] protected void cancelCookie ( HttpServletRequest request , HttpServletResponse response ) { logger . debug ( "Cancelling cookie" ) ; Cookie cookie = new Cookie ( cookieName , null ) ; cookie . setMaxAge ( 0 ) ; cookie . setPath ( getCookiePath ( request ) ) ; if ( cookieDomain != null ) { cookie . setDomain ( cookieDomain ) ; } response . addCookie ( cookie ) ; }


Input: Sets the cookie on the response . [CODESPLIT] protected void setCookie ( String [ ] tokens , int maxAge , HttpServletRequest request , HttpServletResponse response ) { String cookieValue = encodeCookie ( tokens ) ; Cookie cookie = new Cookie ( cookieName , cookieValue ) ; cookie . setMaxAge ( maxAge ) ; cookie . setPath ( getCookiePath ( request ) ) ; if ( cookieDomain != null ) { cookie . setDomain ( cookieDomain ) ; } if ( maxAge < 1 ) { cookie . setVersion ( 1 ) ; } if ( useSecureCookie == null ) { cookie . setSecure ( request . isSecure ( ) ) ; } else { cookie . setSecure ( useSecureCookie ) ; } cookie . setHttpOnly ( true ) ; response . addCookie ( cookie ) ; }


Input: Implementation of { [CODESPLIT] @ Override public void logout ( HttpServletRequest request , HttpServletResponse response , Authentication authentication ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Logout of user " + ( authentication == null ? "Unknown" : authentication . getName ( ) ) ) ; } cancelCookie ( request , response ) ; }


Input: Construct a { @link Converter } for converting a PEM - encoded PKCS#8 RSA Private Key into a { @link RSAPrivateKey } . [CODESPLIT] public static Converter < InputStream , RSAPrivateKey > pkcs8 ( ) { KeyFactory keyFactory = rsaFactory ( ) ; return source -> { List < String > lines = readAllLines ( source ) ; Assert . isTrue ( ! lines . isEmpty ( ) && lines . get ( 0 ) . startsWith ( PKCS8_PEM_HEADER ) , "Key is not in PEM-encoded PKCS#8 format, " + "please check that the header begins with -----" + PKCS8_PEM_HEADER + "-----" ) ; String base64Encoded = lines . stream ( ) . filter ( RsaKeyConverters :: isNotPkcs8Wrapper ) . collect ( Collectors . joining ( ) ) ; byte [ ] pkcs8 = Base64 . getDecoder ( ) . decode ( base64Encoded ) ; try { return ( RSAPrivateKey ) keyFactory . generatePrivate ( new PKCS8EncodedKeySpec ( pkcs8 ) ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( e ) ; } } ; }


Input: Construct a { @link Converter } for converting a PEM - encoded X . 509 RSA Public Key into a { @link RSAPublicKey } . [CODESPLIT] public static Converter < InputStream , RSAPublicKey > x509 ( ) { KeyFactory keyFactory = rsaFactory ( ) ; return source -> { List < String > lines = readAllLines ( source ) ; Assert . isTrue ( ! lines . isEmpty ( ) && lines . get ( 0 ) . startsWith ( X509_PEM_HEADER ) , "Key is not in PEM-encoded X.509 format, " + "please check that the header begins with -----" + X509_PEM_HEADER + "-----" ) ; String base64Encoded = lines . stream ( ) . filter ( RsaKeyConverters :: isNotX509Wrapper ) . collect ( Collectors . joining ( ) ) ; byte [ ] x509 = Base64 . getDecoder ( ) . decode ( base64Encoded ) ; try { return ( RSAPublicKey ) keyFactory . generatePublic ( new X509EncodedKeySpec ( x509 ) ) ; } catch ( Exception e ) { throw new IllegalArgumentException ( e ) ; } } ; }


Input: / * ( non - Javadoc ) [CODESPLIT] @ Override public Mono < Void > writeHttpHeaders ( ServerWebExchange exchange ) { HttpHeaders headers = exchange . getResponse ( ) . getHeaders ( ) ; boolean containsOneHeaderToAdd = Collections . disjoint ( headers . keySet ( ) , this . headersToAdd . keySet ( ) ) ; if ( containsOneHeaderToAdd ) { this . headersToAdd . forEach ( ( name , values ) -> { headers . put ( name , values ) ; } ) ; } return Mono . empty ( ) ; }


Input: Executes the SQL <tt > usersByUsernameQuery< / tt > and returns a list of UserDetails objects . There should normally only be one matching user . [CODESPLIT] protected List < UserDetails > loadUsersByUsername ( String username ) { return getJdbcTemplate ( ) . query ( this . usersByUsernameQuery , new String [ ] { username } , new RowMapper < UserDetails > ( ) { @ Override public UserDetails mapRow ( ResultSet rs , int rowNum ) throws SQLException { String username = rs . getString ( 1 ) ; String password = rs . getString ( 2 ) ; boolean enabled = rs . getBoolean ( 3 ) ; return new User ( username , password , enabled , true , true , true , AuthorityUtils . NO_AUTHORITIES ) ; } } ) ; }


Input: Loads authorities by executing the SQL from <tt > authoritiesByUsernameQuery< / tt > . [CODESPLIT] protected List < GrantedAuthority > loadUserAuthorities ( String username ) { return getJdbcTemplate ( ) . query ( this . authoritiesByUsernameQuery , new String [ ] { username } , new RowMapper < GrantedAuthority > ( ) { @ Override public GrantedAuthority mapRow ( ResultSet rs , int rowNum ) throws SQLException { String roleName = JdbcDaoImpl . this . rolePrefix + rs . getString ( 2 ) ; return new SimpleGrantedAuthority ( roleName ) ; } } ) ; }


Input: Loads authorities by executing the SQL from <tt > groupAuthoritiesByUsernameQuery< / tt > . [CODESPLIT] protected List < GrantedAuthority > loadGroupAuthorities ( String username ) { return getJdbcTemplate ( ) . query ( this . groupAuthoritiesByUsernameQuery , new String [ ] { username } , new RowMapper < GrantedAuthority > ( ) { @ Override public GrantedAuthority mapRow ( ResultSet rs , int rowNum ) throws SQLException { String roleName = getRolePrefix ( ) + rs . getString ( 3 ) ; return new SimpleGrantedAuthority ( roleName ) ; } } ) ; }


Input: Can be overridden to customize the creation of the final UserDetailsObject which is returned by the <tt > loadUserByUsername< / tt > method . [CODESPLIT] protected UserDetails createUserDetails ( String username , UserDetails userFromUserQuery , List < GrantedAuthority > combinedAuthorities ) { String returnUsername = userFromUserQuery . getUsername ( ) ; if ( ! this . usernameBasedPrimaryKey ) { returnUsername = username ; } return new User ( returnUsername , userFromUserQuery . getPassword ( ) , userFromUserQuery . isEnabled ( ) , userFromUserQuery . isAccountNonExpired ( ) , userFromUserQuery . isCredentialsNonExpired ( ) , userFromUserQuery . isAccountNonLocked ( ) , combinedAuthorities ) ; }


Input: / * ( non - Javadoc ) [CODESPLIT] @ Override public void onAuthentication ( Authentication authentication , HttpServletRequest request , HttpServletResponse response ) throws SessionAuthenticationException { boolean containsToken = this . csrfTokenRepository . loadToken ( request ) != null ; if ( containsToken ) { this . csrfTokenRepository . saveToken ( null , request , response ) ; CsrfToken newToken = this . csrfTokenRepository . generateToken ( request ) ; this . csrfTokenRepository . saveToken ( newToken , request , response ) ; request . setAttribute ( CsrfToken . class . getName ( ) , newToken ) ; request . setAttribute ( newToken . getParameterName ( ) , newToken ) ; } }


Input: This concrete implementation simply polls all configured { @link AccessDecisionVoter } s and grants access if any <code > AccessDecisionVoter< / code > voted affirmatively . Denies access only if there was a deny vote AND no affirmative votes . <p > If every <code > AccessDecisionVoter< / code > abstained from voting the decision will be based on the { @link #isAllowIfAllAbstainDecisions () } property ( defaults to false ) . < / p > [CODESPLIT] public void decide ( Authentication authentication , Object object , Collection < ConfigAttribute > configAttributes ) throws AccessDeniedException { int deny = 0 ; for ( AccessDecisionVoter voter : getDecisionVoters ( ) ) { int result = voter . vote ( authentication , object , configAttributes ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Voter: " + voter + ", returned: " + result ) ; } switch ( result ) { case AccessDecisionVoter . ACCESS_GRANTED : return ; case AccessDecisionVoter . ACCESS_DENIED : deny ++ ; break ; default : break ; } } if ( deny > 0 ) { throw new AccessDeniedException ( messages . getMessage ( "AbstractAccessDecisionManager.accessDenied" , "Access is denied" ) ) ; } // To get this far, every AccessDecisionVoter abstained checkAllowIfAllAbstainDecisions ( ) ; }


Input: ======================================================================================================== [CODESPLIT] public void handle ( HttpServletRequest request , HttpServletResponse response , AccessDeniedException accessDeniedException ) throws IOException , ServletException { if ( ! response . isCommitted ( ) ) { if ( errorPage != null ) { // Put exception into request scope (perhaps of use to a view) request . setAttribute ( WebAttributes . ACCESS_DENIED_403 , accessDeniedException ) ; // Set the 403 status code. response . setStatus ( HttpStatus . FORBIDDEN . value ( ) ) ; // forward to error page. RequestDispatcher dispatcher = request . getRequestDispatcher ( errorPage ) ; dispatcher . forward ( request , response ) ; } else { response . sendError ( HttpStatus . FORBIDDEN . value ( ) , HttpStatus . FORBIDDEN . getReasonPhrase ( ) ) ; } } }


Input: The error page to use . Must begin with a / and is interpreted relative to the current context root . [CODESPLIT] public void setErrorPage ( String errorPage ) { if ( ( errorPage != null ) && ! errorPage . startsWith ( "/" ) ) { throw new IllegalArgumentException ( "errorPage must begin with '/'" ) ; } this . errorPage = errorPage ; }


Input: resolve the argument to inject into the controller parameter . [CODESPLIT] @ Override public Mono < Object > resolveArgument ( MethodParameter parameter , BindingContext bindingContext , ServerWebExchange exchange ) { ReactiveAdapter adapter = getAdapterRegistry ( ) . getAdapter ( parameter . getParameterType ( ) ) ; Mono < SecurityContext > reactiveSecurityContext = ReactiveSecurityContextHolder . getContext ( ) ; if ( reactiveSecurityContext == null ) { return null ; } return reactiveSecurityContext . flatMap ( a -> { Object p = resolveSecurityContext ( parameter , a ) ; Mono < Object > o = Mono . justOrEmpty ( p ) ; return adapter == null ? o : Mono . just ( adapter . fromPublisher ( o ) ) ; } ) ; }


Input: resolve the expression from { [CODESPLIT] private Object resolveSecurityContext ( MethodParameter parameter , SecurityContext securityContext ) { CurrentSecurityContext securityContextAnnotation = findMethodAnnotation ( CurrentSecurityContext . class , parameter ) ; Object securityContextResult = securityContext ; String expressionToParse = securityContextAnnotation . expression ( ) ; if ( StringUtils . hasLength ( expressionToParse ) ) { StandardEvaluationContext context = new StandardEvaluationContext ( ) ; context . setRootObject ( securityContext ) ; context . setVariable ( "this" , securityContext ) ; context . setBeanResolver ( beanResolver ) ; Expression expression = this . parser . parseExpression ( expressionToParse ) ; securityContextResult = expression . getValue ( context ) ; } if ( isInvalidType ( parameter , securityContextResult ) ) { if ( securityContextAnnotation . errorOnInvalidType ( ) ) { throw new ClassCastException ( securityContextResult + " is not assignable to " + parameter . getParameterType ( ) ) ; } else { return null ; } } return securityContextResult ; }


Input: If present removes the artifactParameterName and the corresponding value from the query String . [CODESPLIT] private String getQueryString ( final HttpServletRequest request , final Pattern artifactPattern ) { final String query = request . getQueryString ( ) ; if ( query == null ) { return null ; } final String result = artifactPattern . matcher ( query ) . replaceFirst ( "" ) ; if ( result . length ( ) == 0 ) { return null ; } // strip off the trailing & only if the artifact was the first query param return result . startsWith ( "&" ) ? result . substring ( 1 ) : result ; }


Input: Creates a { @link Pattern } that can be passed into the constructor . This allows the { @link Pattern } to be reused for every instance of { @link DefaultServiceAuthenticationDetails } . [CODESPLIT] static Pattern createArtifactPattern ( String artifactParameterName ) { Assert . hasLength ( artifactParameterName , "artifactParameterName is expected to have a length" ) ; return Pattern . compile ( "&?" + Pattern . quote ( artifactParameterName ) + "=[^&]*" ) ; }


Input: Gets the port from the casServiceURL ensuring to return the proper value if the default port is being used . [CODESPLIT] private static int getServicePort ( URL casServiceUrl ) { int port = casServiceUrl . getPort ( ) ; if ( port == - 1 ) { port = casServiceUrl . getDefaultPort ( ) ; } return port ; }


Input: Get the principals of the logged in user in this case the distinguished name . [CODESPLIT] public String getPrincipal ( ) { Authentication authentication = SecurityContextHolder . getContext ( ) . getAuthentication ( ) ; if ( authentication == null ) { log . warn ( "No Authentication object set in SecurityContext - returning empty String as Principal" ) ; return "" ; } Object principal = authentication . getPrincipal ( ) ; if ( principal instanceof LdapUserDetails ) { LdapUserDetails details = ( LdapUserDetails ) principal ; return details . getDn ( ) ; } else if ( authentication instanceof AnonymousAuthenticationToken ) { if ( log . isDebugEnabled ( ) ) { log . debug ( "Anonymous Authentication, returning empty String as Principal" ) ; } return "" ; } else { throw new IllegalArgumentException ( "The principal property of the authentication object" + "needs to be an LdapUserDetails." ) ; } }


Input: / * ( non - Javadoc ) [CODESPLIT] public Object resolveArgument ( MethodParameter parameter , ModelAndViewContainer mavContainer , NativeWebRequest webRequest , WebDataBinderFactory binderFactory ) throws Exception { CsrfToken token = ( CsrfToken ) webRequest . getAttribute ( CsrfToken . class . getName ( ) , NativeWebRequest . SCOPE_REQUEST ) ; return token ; }


Input: ======================================================================================================== [CODESPLIT] public void onApplicationEvent ( AbstractAuthenticationEvent event ) { if ( ! logInteractiveAuthenticationSuccessEvents && event instanceof InteractiveAuthenticationSuccessEvent ) { return ; } if ( logger . isWarnEnabled ( ) ) { final StringBuilder builder = new StringBuilder ( ) ; builder . append ( "Authentication event " ) ; builder . append ( ClassUtils . getShortName ( event . getClass ( ) ) ) ; builder . append ( ": " ) ; builder . append ( event . getAuthentication ( ) . getName ( ) ) ; builder . append ( "; details: " ) ; builder . append ( event . getAuthentication ( ) . getDetails ( ) ) ; if ( event instanceof AbstractAuthenticationFailureEvent ) { builder . append ( "; exception: " ) ; builder . append ( ( ( AbstractAuthenticationFailureEvent ) event ) . getException ( ) . getMessage ( ) ) ; } logger . warn ( builder . toString ( ) ) ; } }


Input: Creates the default MethodInterceptor which is a MethodSecurityInterceptor using the following methods to construct it . <ul > <li > { @link #accessDecisionManager () } < / li > <li > { @link #afterInvocationManager () } < / li > <li > { @link #authenticationManager () } < / li > <li > { @link #methodSecurityMetadataSource () } < / li > <li > { @link #runAsManager () } < / li > [CODESPLIT] @ Bean public MethodInterceptor methodSecurityInterceptor ( ) throws Exception { this . methodSecurityInterceptor = isAspectJ ( ) ? new AspectJMethodSecurityInterceptor ( ) : new MethodSecurityInterceptor ( ) ; methodSecurityInterceptor . setAccessDecisionManager ( accessDecisionManager ( ) ) ; methodSecurityInterceptor . setAfterInvocationManager ( afterInvocationManager ( ) ) ; methodSecurityInterceptor . setSecurityMetadataSource ( methodSecurityMetadataSource ( ) ) ; RunAsManager runAsManager = runAsManager ( ) ; if ( runAsManager != null ) { methodSecurityInterceptor . setRunAsManager ( runAsManager ) ; } return this . methodSecurityInterceptor ; }


Input: / * ( non - Javadoc ) [CODESPLIT] @ Override public void afterSingletonsInstantiated ( ) { try { initializeMethodSecurityInterceptor ( ) ; } catch ( Exception e ) { throw new RuntimeException ( e ) ; } PermissionEvaluator permissionEvaluator = getSingleBeanOrNull ( PermissionEvaluator . class ) ; if ( permissionEvaluator != null ) { this . defaultMethodExpressionHandler . setPermissionEvaluator ( permissionEvaluator ) ; } RoleHierarchy roleHierarchy = getSingleBeanOrNull ( RoleHierarchy . class ) ; if ( roleHierarchy != null ) { this . defaultMethodExpressionHandler . setRoleHierarchy ( roleHierarchy ) ; } AuthenticationTrustResolver trustResolver = getSingleBeanOrNull ( AuthenticationTrustResolver . class ) ; if ( trustResolver != null ) { this . defaultMethodExpressionHandler . setTrustResolver ( trustResolver ) ; } GrantedAuthorityDefaults grantedAuthorityDefaults = getSingleBeanOrNull ( GrantedAuthorityDefaults . class ) ; if ( grantedAuthorityDefaults != null ) { this . defaultMethodExpressionHandler . setDefaultRolePrefix ( grantedAuthorityDefaults . getRolePrefix ( ) ) ; } }


Input: Provide a custom { @link AfterInvocationManager } for the default implementation of { @link #methodSecurityInterceptor () } . The default is null if pre post is not enabled . Otherwise it returns a { @link AfterInvocationProviderManager } . [CODESPLIT] protected AfterInvocationManager afterInvocationManager ( ) { if ( prePostEnabled ( ) ) { AfterInvocationProviderManager invocationProviderManager = new AfterInvocationProviderManager ( ) ; ExpressionBasedPostInvocationAdvice postAdvice = new ExpressionBasedPostInvocationAdvice ( getExpressionHandler ( ) ) ; PostInvocationAdviceProvider postInvocationAdviceProvider = new PostInvocationAdviceProvider ( postAdvice ) ; List < AfterInvocationProvider > afterInvocationProviders = new ArrayList <> ( ) ; afterInvocationProviders . add ( postInvocationAdviceProvider ) ; invocationProviderManager . setProviders ( afterInvocationProviders ) ; return invocationProviderManager ; } return null ; }


Input: Allows subclasses to provide a custom { @link AccessDecisionManager } . The default is a { @link AffirmativeBased } with the following voters : [CODESPLIT] protected AccessDecisionManager accessDecisionManager ( ) { List < AccessDecisionVoter < ? extends Object > > decisionVoters = new ArrayList < AccessDecisionVoter < ? extends Object > > ( ) ; ExpressionBasedPreInvocationAdvice expressionAdvice = new ExpressionBasedPreInvocationAdvice ( ) ; expressionAdvice . setExpressionHandler ( getExpressionHandler ( ) ) ; if ( prePostEnabled ( ) ) { decisionVoters . add ( new PreInvocationAuthorizationAdviceVoter ( expressionAdvice ) ) ; } if ( jsr250Enabled ( ) ) { decisionVoters . add ( new Jsr250Voter ( ) ) ; } RoleVoter roleVoter = new RoleVoter ( ) ; GrantedAuthorityDefaults grantedAuthorityDefaults = getSingleBeanOrNull ( GrantedAuthorityDefaults . class ) ; if ( grantedAuthorityDefaults != null ) { roleVoter . setRolePrefix ( grantedAuthorityDefaults . getRolePrefix ( ) ) ; } decisionVoters . add ( roleVoter ) ; decisionVoters . add ( new AuthenticatedVoter ( ) ) ; return new AffirmativeBased ( decisionVoters ) ; }


Input: Allows providing a custom { @link AuthenticationManager } . The default is to use any authentication mechanisms registered by { @link #configure ( AuthenticationManagerBuilder ) } . If { @link #configure ( AuthenticationManagerBuilder ) } was not overridden then an { @link AuthenticationManager } is attempted to be autowired by type . [CODESPLIT] protected AuthenticationManager authenticationManager ( ) throws Exception { if ( authenticationManager == null ) { DefaultAuthenticationEventPublisher eventPublisher = objectPostProcessor . postProcess ( new DefaultAuthenticationEventPublisher ( ) ) ; auth = new AuthenticationManagerBuilder ( objectPostProcessor ) ; auth . authenticationEventPublisher ( eventPublisher ) ; configure ( auth ) ; if ( disableAuthenticationRegistry ) { authenticationManager = getAuthenticationConfiguration ( ) . getAuthenticationManager ( ) ; } else { authenticationManager = auth . build ( ) ; } } return authenticationManager ; }


Input: Provides the default { @link MethodSecurityMetadataSource } that will be used . It creates a { @link DelegatingMethodSecurityMetadataSource } based upon { @link #customMethodSecurityMetadataSource () } and the attributes on { @link EnableGlobalMethodSecurity } . [CODESPLIT] @ Bean public MethodSecurityMetadataSource methodSecurityMetadataSource ( ) { List < MethodSecurityMetadataSource > sources = new ArrayList <> ( ) ; ExpressionBasedAnnotationAttributeFactory attributeFactory = new ExpressionBasedAnnotationAttributeFactory ( getExpressionHandler ( ) ) ; MethodSecurityMetadataSource customMethodSecurityMetadataSource = customMethodSecurityMetadataSource ( ) ; if ( customMethodSecurityMetadataSource != null ) { sources . add ( customMethodSecurityMetadataSource ) ; } boolean hasCustom = customMethodSecurityMetadataSource != null ; boolean isPrePostEnabled = prePostEnabled ( ) ; boolean isSecuredEnabled = securedEnabled ( ) ; boolean isJsr250Enabled = jsr250Enabled ( ) ; if ( ! isPrePostEnabled && ! isSecuredEnabled && ! isJsr250Enabled && ! hasCustom ) { throw new IllegalStateException ( "In the composition of all global method configuration, " + "no annotation support was actually activated" ) ; } if ( isPrePostEnabled ) { sources . add ( new PrePostAnnotationSecurityMetadataSource ( attributeFactory ) ) ; } if ( isSecuredEnabled ) { sources . add ( new SecuredAnnotationSecurityMetadataSource ( ) ) ; } if ( isJsr250Enabled ) { GrantedAuthorityDefaults grantedAuthorityDefaults = getSingleBeanOrNull ( GrantedAuthorityDefaults . class ) ; Jsr250MethodSecurityMetadataSource jsr250MethodSecurityMetadataSource = this . context . getBean ( Jsr250MethodSecurityMetadataSource . class ) ; if ( grantedAuthorityDefaults != null ) { jsr250MethodSecurityMetadataSource . setDefaultRolePrefix ( grantedAuthorityDefaults . getRolePrefix ( ) ) ; } sources . add ( jsr250MethodSecurityMetadataSource ) ; } return new DelegatingMethodSecurityMetadataSource ( sources ) ; }


Input: Creates the { @link PreInvocationAuthorizationAdvice } to be used . The default is { @link ExpressionBasedPreInvocationAdvice } . [CODESPLIT] @ Bean public PreInvocationAuthorizationAdvice preInvocationAuthorizationAdvice ( ) { ExpressionBasedPreInvocationAdvice preInvocationAdvice = new ExpressionBasedPreInvocationAdvice ( ) ; preInvocationAdvice . setExpressionHandler ( getExpressionHandler ( ) ) ; return preInvocationAdvice ; }


Input: Obtains the attributes from { [CODESPLIT] public final void setImportMetadata ( AnnotationMetadata importMetadata ) { Map < String , Object > annotationAttributes = importMetadata . getAnnotationAttributes ( EnableGlobalMethodSecurity . class . getName ( ) ) ; enableMethodSecurity = AnnotationAttributes . fromMap ( annotationAttributes ) ; }


Input: ======================================================================================================== [CODESPLIT] @ Override public AppConfigurationEntry [ ] getAppConfigurationEntry ( String name ) { AppConfigurationEntry [ ] mappedResult = this . mappedConfigurations . get ( name ) ; return mappedResult == null ? this . defaultConfiguration : mappedResult ; }


Input: { [CODESPLIT] @ Override public String resolve ( HttpServletRequest request ) { String authorizationHeaderToken = resolveFromAuthorizationHeader ( request ) ; String parameterToken = resolveFromRequestParameters ( request ) ; if ( authorizationHeaderToken != null ) { if ( parameterToken != null ) { BearerTokenError error = new BearerTokenError ( BearerTokenErrorCodes . INVALID_REQUEST , HttpStatus . BAD_REQUEST , "Found multiple bearer tokens in the request" , "https://tools.ietf.org/html/rfc6750#section-3.1" ) ; throw new OAuth2AuthenticationException ( error ) ; } return authorizationHeaderToken ; } else if ( parameterToken != null && isParameterTokenSupportedForRequest ( request ) ) { return parameterToken ; } return null ; }


Input: Construct a { @link MappedJwtClaimSetConverter } overriding individual claim converters with the provided { @link Map } of { @link Converter } s . [CODESPLIT] public static MappedJwtClaimSetConverter withDefaults ( Map < String , Converter < Object , ? > > claimConverters ) { Assert . notNull ( claimConverters , "claimConverters cannot be null" ) ; Map < String , Converter < Object , ? > > claimNameToConverter = new HashMap <> ( ) ; claimNameToConverter . put ( JwtClaimNames . AUD , AUDIENCE_CONVERTER ) ; claimNameToConverter . put ( JwtClaimNames . EXP , TEMPORAL_CONVERTER ) ; claimNameToConverter . put ( JwtClaimNames . IAT , TEMPORAL_CONVERTER ) ; claimNameToConverter . put ( JwtClaimNames . ISS , ISSUER_CONVERTER ) ; claimNameToConverter . put ( JwtClaimNames . JTI , STRING_CONVERTER ) ; claimNameToConverter . put ( JwtClaimNames . NBF , TEMPORAL_CONVERTER ) ; claimNameToConverter . put ( JwtClaimNames . SUB , STRING_CONVERTER ) ; claimNameToConverter . putAll ( claimConverters ) ; return new MappedJwtClaimSetConverter ( claimNameToConverter ) ; }


Input: { [CODESPLIT] @ Override public Map < String , Object > convert ( Map < String , Object > claims ) { Assert . notNull ( claims , "claims cannot be null" ) ; Map < String , Object > mappedClaims = new HashMap <> ( claims ) ; for ( Map . Entry < String , Converter < Object , ? > > entry : this . claimConverters . entrySet ( ) ) { String claimName = entry . getKey ( ) ; Converter < Object , ? > converter = entry . getValue ( ) ; if ( converter != null ) { Object claim = claims . get ( claimName ) ; Object mappedClaim = converter . convert ( claim ) ; mappedClaims . compute ( claimName , ( key , value ) -> mappedClaim ) ; } } Instant issuedAt = ( Instant ) mappedClaims . get ( JwtClaimNames . IAT ) ; Instant expiresAt = ( Instant ) mappedClaims . get ( JwtClaimNames . EXP ) ; if ( issuedAt == null && expiresAt != null ) { mappedClaims . put ( JwtClaimNames . IAT , expiresAt . minusSeconds ( 1 ) ) ; } return mappedClaims ; }


Input: Returns true if the configured pattern ( and HTTP - Method ) match those of the supplied request . [CODESPLIT] @ Override public boolean matches ( HttpServletRequest request ) { if ( this . httpMethod != null && StringUtils . hasText ( request . getMethod ( ) ) && this . httpMethod != valueOf ( request . getMethod ( ) ) ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Request '" + request . getMethod ( ) + " " + getRequestPath ( request ) + "'" + " doesn't match '" + this . httpMethod + " " + this . pattern + "'" ) ; } return false ; } if ( this . pattern . equals ( MATCH_ALL ) ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Request '" + getRequestPath ( request ) + "' matched by universal pattern '/**'" ) ; } return true ; } String url = getRequestPath ( request ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Checking match of request : '" + url + "'; against '" + this . pattern + "'" ) ; } return this . matcher . matches ( url ) ; }


Input: Method that is actually called by the filter chain . Simply delegates to the { @link #invoke ( FilterInvocation ) } method . [CODESPLIT] public void doFilter ( ServletRequest request , ServletResponse response , FilterChain chain ) throws IOException , ServletException { FilterInvocation fi = new FilterInvocation ( request , response , chain ) ; invoke ( fi ) ; }


Input: Sets the map of exception types ( by name ) to URLs . [CODESPLIT] public void setExceptionMappings ( Map < ? , ? > failureUrlMap ) { this . failureUrlMap . clear ( ) ; for ( Map . Entry < ? , ? > entry : failureUrlMap . entrySet ( ) ) { Object exception = entry . getKey ( ) ; Object url = entry . getValue ( ) ; Assert . isInstanceOf ( String . class , exception , "Exception key must be a String (the exception classname)." ) ; Assert . isInstanceOf ( String . class , url , "URL must be a String" ) ; Assert . isTrue ( UrlUtils . isValidRedirectUrl ( ( String ) url ) , ( ) -> "Not a valid redirect URL: " + url ) ; this . failureUrlMap . put ( ( String ) exception , ( String ) url ) ; } }


Input: Adds a { [CODESPLIT] public ServerHttpSecurity addFilterAfter ( WebFilter webFilter , SecurityWebFiltersOrder order ) { this . webFilters . add ( new OrderedWebFilter ( webFilter , order . getOrder ( ) + 1 ) ) ; return this ; }


Input: Builds the { [CODESPLIT] public SecurityWebFilterChain build ( ) { if ( this . built != null ) { throw new IllegalStateException ( "This has already been built with the following stacktrace. " + buildToString ( ) ) ; } this . built = new RuntimeException ( "First Build Invocation" ) . fillInStackTrace ( ) ; if ( this . headers != null ) { this . headers . configure ( this ) ; } WebFilter securityContextRepositoryWebFilter = securityContextRepositoryWebFilter ( ) ; if ( securityContextRepositoryWebFilter != null ) { this . webFilters . add ( securityContextRepositoryWebFilter ) ; } if ( this . httpsRedirectSpec != null ) { this . httpsRedirectSpec . configure ( this ) ; } if ( this . x509 != null ) { this . x509 . configure ( this ) ; } if ( this . csrf != null ) { this . csrf . configure ( this ) ; } if ( this . cors != null ) { this . cors . configure ( this ) ; } if ( this . httpBasic != null ) { this . httpBasic . authenticationManager ( this . authenticationManager ) ; this . httpBasic . configure ( this ) ; } if ( this . formLogin != null ) { this . formLogin . authenticationManager ( this . authenticationManager ) ; if ( this . securityContextRepository != null ) { this . formLogin . securityContextRepository ( this . securityContextRepository ) ; } this . formLogin . configure ( this ) ; } if ( this . oauth2Login != null ) { this . oauth2Login . configure ( this ) ; } if ( this . resourceServer != null ) { this . resourceServer . configure ( this ) ; } if ( this . client != null ) { this . client . configure ( this ) ; } if ( this . anonymous != null ) { this . anonymous . configure ( this ) ; } this . loginPage . configure ( this ) ; if ( this . logout != null ) { this . logout . configure ( this ) ; } this . requestCache . configure ( this ) ; this . addFilterAt ( new SecurityContextServerWebExchangeWebFilter ( ) , SecurityWebFiltersOrder . SECURITY_CONTEXT_SERVER_WEB_EXCHANGE ) ; if ( this . authorizeExchange != null ) { ServerAuthenticationEntryPoint authenticationEntryPoint = getAuthenticationEntryPoint ( ) ; ExceptionTranslationWebFilter exceptionTranslationWebFilter = new ExceptionTranslationWebFilter ( ) ; if ( authenticationEntryPoint != null ) { exceptionTranslationWebFilter . setAuthenticationEntryPoint ( authenticationEntryPoint ) ; } ServerAccessDeniedHandler accessDeniedHandler = getAccessDeniedHandler ( ) ; if ( accessDeniedHandler != null ) { exceptionTranslationWebFilter . setAccessDeniedHandler ( accessDeniedHandler ) ; } this . addFilterAt ( exceptionTranslationWebFilter , SecurityWebFiltersOrder . EXCEPTION_TRANSLATION ) ; this . authorizeExchange . configure ( this ) ; } AnnotationAwareOrderComparator . sort ( this . webFilters ) ; List < WebFilter > sortedWebFilters = new ArrayList <> ( ) ; this . webFilters . forEach ( f -> { if ( f instanceof OrderedWebFilter ) { f = ( ( OrderedWebFilter ) f ) . webFilter ; } sortedWebFilters . add ( f ) ; } ) ; sortedWebFilters . add ( 0 , new ServerWebExchangeReactorContextWebFilter ( ) ) ; return new MatcherSecurityWebFilterChain ( getSecurityMatcher ( ) , sortedWebFilters ) ; }


Input: Requires the request to be passed in . [CODESPLIT] public void logout ( HttpServletRequest request , HttpServletResponse response , Authentication authentication ) { Assert . notNull ( request , "HttpServletRequest required" ) ; if ( invalidateHttpSession ) { HttpSession session = request . getSession ( false ) ; if ( session != null ) { logger . debug ( "Invalidating session: " + session . getId ( ) ) ; session . invalidate ( ) ; } } if ( clearAuthentication ) { SecurityContext context = SecurityContextHolder . getContext ( ) ; context . setAuthentication ( null ) ; } SecurityContextHolder . clearContext ( ) ; }


Input: Implementation of { @link ServerLogoutSuccessHandler#onLogoutSuccess ( WebFilterExchange Authentication ) } . Sets the status on the { @link WebFilterExchange } . [CODESPLIT] @ Override public Mono < Void > onLogoutSuccess ( WebFilterExchange exchange , Authentication authentication ) { return Mono . fromRunnable ( ( ) -> exchange . getExchange ( ) . getResponse ( ) . setStatusCode ( this . httpStatusToReturn ) ) ; }


Input: Validates the required properties are set . In addition if { [CODESPLIT] public void afterPropertiesSet ( ) throws Exception { Assert . hasLength ( this . loginContextName , "loginContextName cannot be null or empty" ) ; Assert . notEmpty ( this . authorityGranters , "authorityGranters cannot be null or empty" ) ; if ( ObjectUtils . isEmpty ( this . callbackHandlers ) ) { setCallbackHandlers ( new JaasAuthenticationCallbackHandler [ ] { new JaasNameCallbackHandler ( ) , new JaasPasswordCallbackHandler ( ) } ) ; } Assert . notNull ( this . loginExceptionResolver , "loginExceptionResolver cannot be null" ) ; }


Input: Attempts to login the user given the Authentication objects principal and credential [CODESPLIT] public Authentication authenticate ( Authentication auth ) throws AuthenticationException { if ( ! ( auth instanceof UsernamePasswordAuthenticationToken ) ) { return null ; } UsernamePasswordAuthenticationToken request = ( UsernamePasswordAuthenticationToken ) auth ; Set < GrantedAuthority > authorities ; try { // Create the LoginContext object, and pass our InternallCallbackHandler LoginContext loginContext = createLoginContext ( new InternalCallbackHandler ( auth ) ) ; // Attempt to login the user, the LoginContext will call our // InternalCallbackHandler at this point. loginContext . login ( ) ; // Create a set to hold the authorities, and add any that have already been // applied. authorities = new HashSet <> ( ) ; // Get the subject principals and pass them to each of the AuthorityGranters Set < Principal > principals = loginContext . getSubject ( ) . getPrincipals ( ) ; for ( Principal principal : principals ) { for ( AuthorityGranter granter : this . authorityGranters ) { Set < String > roles = granter . grant ( principal ) ; // If the granter doesn't wish to grant any authorities, it should // return null. if ( ( roles != null ) && ! roles . isEmpty ( ) ) { for ( String role : roles ) { authorities . add ( new JaasGrantedAuthority ( role , principal ) ) ; } } } } // Convert the authorities set back to an array and apply it to the token. JaasAuthenticationToken result = new JaasAuthenticationToken ( request . getPrincipal ( ) , request . getCredentials ( ) , new ArrayList <> ( authorities ) , loginContext ) ; // Publish the success event publishSuccessEvent ( result ) ; // we're done, return the token. return result ; } catch ( LoginException loginException ) { AuthenticationException ase = this . loginExceptionResolver . resolveException ( loginException ) ; publishFailureEvent ( request , ase ) ; throw ase ; } }


Input: Handles the logout by getting the security contexts for the destroyed session and invoking { @code LoginContext . logout () } for any which contain a { @code JaasAuthenticationToken } . [CODESPLIT] protected void handleLogout ( SessionDestroyedEvent event ) { List < SecurityContext > contexts = event . getSecurityContexts ( ) ; if ( contexts . isEmpty ( ) ) { this . log . debug ( "The destroyed session has no SecurityContexts" ) ; return ; } for ( SecurityContext context : contexts ) { Authentication auth = context . getAuthentication ( ) ; if ( ( auth != null ) && ( auth instanceof JaasAuthenticationToken ) ) { JaasAuthenticationToken token = ( JaasAuthenticationToken ) auth ; try { LoginContext loginContext = token . getLoginContext ( ) ; boolean debug = this . log . isDebugEnabled ( ) ; if ( loginContext != null ) { if ( debug ) { this . log . debug ( "Logging principal: [" + token . getPrincipal ( ) + "] out of LoginContext" ) ; } loginContext . logout ( ) ; } else if ( debug ) { this . log . debug ( "Cannot logout principal: [" + token . getPrincipal ( ) + "] from LoginContext. " + "The LoginContext is unavailable" ) ; } } catch ( LoginException e ) { this . log . warn ( "Error error logging out of LoginContext" , e ) ; } } } }


Input: Publishes the { @link JaasAuthenticationFailedEvent } . Can be overridden by subclasses for different functionality [CODESPLIT] protected void publishFailureEvent ( UsernamePasswordAuthenticationToken token , AuthenticationException ase ) { if ( this . applicationEventPublisher != null ) { this . applicationEventPublisher . publishEvent ( new JaasAuthenticationFailedEvent ( token , ase ) ) ; } }


Input: Factory method for creating a { @link DelegatingSecurityContextRunnable } . [CODESPLIT] public static Runnable create ( Runnable delegate , SecurityContext securityContext ) { Assert . notNull ( delegate , "delegate cannot be  null" ) ; return securityContext == null ? new DelegatingSecurityContextRunnable ( delegate ) : new DelegatingSecurityContextRunnable ( delegate , securityContext ) ; }


Input: ======================================================================================================== [CODESPLIT] public Collection < ConfigAttribute > getAllConfigAttributes ( ) { Set < ConfigAttribute > allAttributes = new HashSet <> ( ) ; for ( Map . Entry < RequestMatcher , Collection < ConfigAttribute > > entry : requestMap . entrySet ( ) ) { allAttributes . addAll ( entry . getValue ( ) ) ; } return allAttributes ; }


Input: Set all authorities for this user from String values . It will create the necessary { @link GrantedAuthority } objects . [CODESPLIT] public void setAuthoritiesAsString ( List < String > authoritiesAsStrings ) { setAuthorities ( new ArrayList <> ( authoritiesAsStrings . size ( ) ) ) ; for ( String authority : authoritiesAsStrings ) { addAuthority ( new SimpleGrantedAuthority ( authority ) ) ; } }


Input: Sets the provided value as a Bearer token in a header with the name of { [CODESPLIT] public static Consumer < HttpHeaders > bearerToken ( String bearerTokenValue ) { Assert . hasText ( bearerTokenValue , "bearerTokenValue cannot be null" ) ; return headers -> headers . set ( HttpHeaders . AUTHORIZATION , "Bearer " + bearerTokenValue ) ; }


Input: Builds a Spring LDAP - compliant Provider URL string i . e . a space - separated list of LDAP servers with their base DNs . As the base DN must be identical for all servers it needs to be supplied only once . [CODESPLIT] private static String buildProviderUrl ( List < String > urls , String baseDn ) { Assert . notNull ( baseDn , "The Base DN for the LDAP server must not be null." ) ; Assert . notEmpty ( urls , "At least one LDAP server URL must be provided." ) ; String trimmedBaseDn = baseDn . trim ( ) ; StringBuilder providerUrl = new StringBuilder ( ) ; for ( String serverUrl : urls ) { String trimmedUrl = serverUrl . trim ( ) ; if ( "" . equals ( trimmedUrl ) ) { continue ; } providerUrl . append ( trimmedUrl ) ; if ( ! trimmedUrl . endsWith ( "/" ) ) { providerUrl . append ( "/" ) ; } providerUrl . append ( trimmedBaseDn ) ; providerUrl . append ( " " ) ; } return providerUrl . toString ( ) ; }


Input: Creates the user authority list from the values of the { [CODESPLIT] @ Override protected Collection < ? extends GrantedAuthority > loadUserAuthorities ( DirContextOperations userData , String username , String password ) { String [ ] groups = userData . getStringAttributes ( "memberOf" ) ; if ( groups == null ) { logger . debug ( "No values for 'memberOf' attribute." ) ; return AuthorityUtils . NO_AUTHORITIES ; } if ( logger . isDebugEnabled ( ) ) { logger . debug ( "'memberOf' attribute values: " + Arrays . asList ( groups ) ) ; } ArrayList < GrantedAuthority > authorities = new ArrayList <> ( groups . length ) ; for ( String group : groups ) { authorities . add ( new SimpleGrantedAuthority ( new DistinguishedName ( group ) . removeLast ( ) . getValue ( ) ) ) ; } return authorities ; }


Input: Allows a custom environment properties to be used to create initial LDAP context . [CODESPLIT] public void setContextEnvironmentProperties ( Map < String , Object > environment ) { Assert . notEmpty ( environment , "environment must not be empty" ) ; this . contextEnvironmentProperties = new Hashtable <> ( environment ) ; }


Input: Gets the state parameter from the { [CODESPLIT] private String getStateParameter ( ServerWebExchange exchange ) { Assert . notNull ( exchange , "exchange cannot be null" ) ; return exchange . getRequest ( ) . getQueryParams ( ) . getFirst ( OAuth2ParameterNames . STATE ) ; }


Input: Determines if the current request matches the <code > DefaultSavedRequest< / code > . <p > All URL arguments are considered but not cookies locales headers or parameters . [CODESPLIT] public boolean doesRequestMatch ( HttpServletRequest request , PortResolver portResolver ) { if ( ! propertyEquals ( "pathInfo" , this . pathInfo , request . getPathInfo ( ) ) ) { return false ; } if ( ! propertyEquals ( "queryString" , this . queryString , request . getQueryString ( ) ) ) { return false ; } if ( ! propertyEquals ( "requestURI" , this . requestURI , request . getRequestURI ( ) ) ) { return false ; } if ( ! "GET" . equals ( request . getMethod ( ) ) && "GET" . equals ( method ) ) { // A save GET should not match an incoming non-GET method return false ; } if ( ! propertyEquals ( "serverPort" , Integer . valueOf ( this . serverPort ) , Integer . valueOf ( portResolver . getServerPort ( request ) ) ) ) { return false ; } if ( ! propertyEquals ( "requestURL" , this . requestURL , request . getRequestURL ( ) . toString ( ) ) ) { return false ; } if ( ! propertyEquals ( "scheme" , this . scheme , request . getScheme ( ) ) ) { return false ; } if ( ! propertyEquals ( "serverName" , this . serverName , request . getServerName ( ) ) ) { return false ; } if ( ! propertyEquals ( "contextPath" , this . contextPath , request . getContextPath ( ) ) ) { return false ; } return propertyEquals ( "servletPath" , this . servletPath , request . getServletPath ( ) ) ; }


Input: Indicates the URL that the user agent used for this request . [CODESPLIT] @ Override public String getRedirectUrl ( ) { return UrlUtils . buildFullRequestUrl ( scheme , serverName , serverPort , requestURI , queryString ) ; }


Input: Use the following { @link Converter } for manipulating the JWT s claim set [CODESPLIT] public void setClaimSetConverter ( Converter < Map < String , Object > , Map < String , Object > > claimSetConverter ) { Assert . notNull ( claimSetConverter , "claimSetConverter cannot be null" ) ; this . claimSetConverter = claimSetConverter ; }


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


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 ( ) ; if ( principal != null && ! parameter . getParameterType ( ) . isAssignableFrom ( principal . getClass ( ) ) ) { AuthenticationPrincipal authPrincipal = findMethodAnnotation ( AuthenticationPrincipal . class , parameter ) ; if ( authPrincipal . errorOnInvalidType ( ) ) { throw new ClassCastException ( principal + " is not assignable to " + parameter . getParameterType ( ) ) ; } else { return null ; } } return principal ; }


Input: Creates a { @link JwtDecoder } using the provided  Issuer by making an  OpenID Provider Configuration Request and using the values in the  OpenID Provider Configuration Response to initialize the { @link JwtDecoder } . [CODESPLIT] public static JwtDecoder fromOidcIssuerLocation ( String oidcIssuerLocation ) { Map < String , Object > openidConfiguration = getOpenidConfiguration ( oidcIssuerLocation ) ; String metadataIssuer = "(unavailable)" ; if ( openidConfiguration . containsKey ( "issuer" ) ) { metadataIssuer = openidConfiguration . get ( "issuer" ) . toString ( ) ; } if ( ! oidcIssuerLocation . equals ( metadataIssuer ) ) { throw new IllegalStateException ( "The Issuer \"" + metadataIssuer + "\" provided in the OpenID Configuration " + "did not match the requested issuer \"" + oidcIssuerLocation + "\"" ) ; } OAuth2TokenValidator < Jwt > jwtValidator = JwtValidators . createDefaultWithIssuer ( oidcIssuerLocation ) ; NimbusJwtDecoder jwtDecoder = withJwkSetUri ( openidConfiguration . get ( "jwks_uri" ) . toString ( ) ) . build ( ) ; jwtDecoder . setJwtValidator ( jwtValidator ) ; return jwtDecoder ; }


Input: The aim of this method is to build the list of filters which have been defined by the namespace elements and attributes within the &lt ; http&gt ; configuration along with any custom - filter s linked to user - defined filter beans . <p > By the end of this method the default <tt > FilterChainProxy< / tt > bean should have been registered and will have the map of filter chains defined with the universal match pattern mapped to the list of beans which have been parsed here . [CODESPLIT] @ SuppressWarnings ( { "unchecked" } ) @ Override public BeanDefinition parse ( Element element , ParserContext pc ) { CompositeComponentDefinition compositeDef = new CompositeComponentDefinition ( element . getTagName ( ) , pc . extractSource ( element ) ) ; pc . pushContainingComponent ( compositeDef ) ; registerFilterChainProxyIfNecessary ( pc , pc . extractSource ( element ) ) ; // Obtain the filter chains and add the new chain to it BeanDefinition listFactoryBean = pc . getRegistry ( ) . getBeanDefinition ( BeanIds . FILTER_CHAINS ) ; List < BeanReference > filterChains = ( List < BeanReference > ) listFactoryBean . getPropertyValues ( ) . getPropertyValue ( "sourceList" ) . getValue ( ) ; filterChains . add ( createFilterChain ( element , pc ) ) ; pc . popAndRegisterContainingComponent ( ) ; return null ; }


Input: Creates the { [CODESPLIT] private BeanReference createFilterChain ( Element element , ParserContext pc ) { boolean secured = ! OPT_SECURITY_NONE . equals ( element . getAttribute ( ATT_SECURED ) ) ; if ( ! secured ) { if ( ! StringUtils . hasText ( element . getAttribute ( ATT_PATH_PATTERN ) ) && ! StringUtils . hasText ( ATT_REQUEST_MATCHER_REF ) ) { pc . getReaderContext ( ) . error ( "The '" + ATT_SECURED + "' attribute must be used in combination with" + " the '" + ATT_PATH_PATTERN + "' or '" + ATT_REQUEST_MATCHER_REF + "' attributes." , pc . extractSource ( element ) ) ; } for ( int n = 0 ; n < element . getChildNodes ( ) . getLength ( ) ; n ++ ) { if ( element . getChildNodes ( ) . item ( n ) instanceof Element ) { pc . getReaderContext ( ) . error ( "If you are using <http> to define an unsecured pattern, " + "it cannot contain child elements." , pc . extractSource ( element ) ) ; } } return createSecurityFilterChainBean ( element , pc , Collections . emptyList ( ) ) ; } final BeanReference portMapper = createPortMapper ( element , pc ) ; final BeanReference portResolver = createPortResolver ( portMapper , pc ) ; ManagedList < BeanReference > authenticationProviders = new ManagedList <> ( ) ; BeanReference authenticationManager = createAuthenticationManager ( element , pc , authenticationProviders ) ; boolean forceAutoConfig = isDefaultHttpConfig ( element ) ; HttpConfigurationBuilder httpBldr = new HttpConfigurationBuilder ( element , forceAutoConfig , pc , portMapper , portResolver , authenticationManager ) ; AuthenticationConfigBuilder authBldr = new AuthenticationConfigBuilder ( element , forceAutoConfig , pc , httpBldr . getSessionCreationPolicy ( ) , httpBldr . getRequestCache ( ) , authenticationManager , httpBldr . getSessionStrategy ( ) , portMapper , portResolver , httpBldr . getCsrfLogoutHandler ( ) ) ; httpBldr . setLogoutHandlers ( authBldr . getLogoutHandlers ( ) ) ; httpBldr . setEntryPoint ( authBldr . getEntryPointBean ( ) ) ; httpBldr . setAccessDeniedHandler ( authBldr . getAccessDeniedHandlerBean ( ) ) ; authenticationProviders . addAll ( authBldr . getProviders ( ) ) ; List < OrderDecorator > unorderedFilterChain = new ArrayList <> ( ) ; unorderedFilterChain . addAll ( httpBldr . getFilters ( ) ) ; unorderedFilterChain . addAll ( authBldr . getFilters ( ) ) ; unorderedFilterChain . addAll ( buildCustomFilterList ( element , pc ) ) ; Collections . sort ( unorderedFilterChain , new OrderComparator ( ) ) ; checkFilterChainOrder ( unorderedFilterChain , pc , pc . extractSource ( element ) ) ; // The list of filter beans List < BeanMetadataElement > filterChain = new ManagedList <> ( ) ; for ( OrderDecorator od : unorderedFilterChain ) { filterChain . add ( od . bean ) ; } return createSecurityFilterChainBean ( element , pc , filterChain ) ; }


Input: Creates the internal AuthenticationManager bean which uses either the externally registered ( global ) one as a parent or the bean specified by authentication - manager - ref . [CODESPLIT] private BeanReference createAuthenticationManager ( Element element , ParserContext pc , ManagedList < BeanReference > authenticationProviders ) { String parentMgrRef = element . getAttribute ( ATT_AUTHENTICATION_MANAGER_REF ) ; BeanDefinitionBuilder authManager = BeanDefinitionBuilder . rootBeanDefinition ( ProviderManager . class ) ; authManager . addConstructorArgValue ( authenticationProviders ) ; if ( StringUtils . hasText ( parentMgrRef ) ) { RuntimeBeanReference parentAuthManager = new RuntimeBeanReference ( parentMgrRef ) ; authManager . addConstructorArgValue ( parentAuthManager ) ; RootBeanDefinition clearCredentials = new RootBeanDefinition ( ClearCredentialsMethodInvokingFactoryBean . class ) ; clearCredentials . getPropertyValues ( ) . addPropertyValue ( "targetObject" , parentAuthManager ) ; clearCredentials . getPropertyValues ( ) . addPropertyValue ( "targetMethod" , "isEraseCredentialsAfterAuthentication" ) ; authManager . addPropertyValue ( "eraseCredentialsAfterAuthentication" , clearCredentials ) ; } else { RootBeanDefinition amfb = new RootBeanDefinition ( AuthenticationManagerFactoryBean . class ) ; amfb . setRole ( BeanDefinition . ROLE_INFRASTRUCTURE ) ; String amfbId = pc . getReaderContext ( ) . generateBeanName ( amfb ) ; pc . registerBeanComponent ( new BeanComponentDefinition ( amfb , amfbId ) ) ; RootBeanDefinition clearCredentials = new RootBeanDefinition ( MethodInvokingFactoryBean . class ) ; clearCredentials . getPropertyValues ( ) . addPropertyValue ( "targetObject" , new RuntimeBeanReference ( amfbId ) ) ; clearCredentials . getPropertyValues ( ) . addPropertyValue ( "targetMethod" , "isEraseCredentialsAfterAuthentication" ) ; authManager . addConstructorArgValue ( new RuntimeBeanReference ( amfbId ) ) ; authManager . addPropertyValue ( "eraseCredentialsAfterAuthentication" , clearCredentials ) ; } authManager . getRawBeanDefinition ( ) . setSource ( pc . extractSource ( element ) ) ; BeanDefinition authMgrBean = authManager . getBeanDefinition ( ) ; String id = pc . getReaderContext ( ) . generateBeanName ( authMgrBean ) ; pc . registerBeanComponent ( new BeanComponentDefinition ( authMgrBean , id ) ) ; return new RuntimeBeanReference ( id ) ; }


Input: { [CODESPLIT] @ Override public OAuth2TokenValidatorResult validate ( T token ) { Collection < OAuth2Error > errors = new ArrayList <> ( ) ; for ( OAuth2TokenValidator < T > validator : this . tokenValidators ) { errors . addAll ( validator . validate ( token ) . getErrors ( ) ) ; } return OAuth2TokenValidatorResult . failure ( errors ) ; }


Input: Invokes the base class { @link AbstractAuthorizeTag#authorize () } method to decide if the body of the tag should be skipped or not . [CODESPLIT] public int doStartTag ( ) throws JspException { try { authorized = super . authorize ( ) ; if ( ! authorized && TagLibConfig . isUiSecurityDisabled ( ) ) { pageContext . getOut ( ) . write ( TagLibConfig . getSecuredUiPrefix ( ) ) ; } if ( var != null ) { pageContext . setAttribute ( var , authorized , PageContext . PAGE_SCOPE ) ; } return TagLibConfig . evalOrSkip ( authorized ) ; } catch ( IOException e ) { throw new JspException ( e ) ; } }


Input: Default processing of the end tag returning EVAL_PAGE . [CODESPLIT] public int doEndTag ( ) throws JspException { try { if ( ! authorized && TagLibConfig . isUiSecurityDisabled ( ) ) { pageContext . getOut ( ) . write ( TagLibConfig . getSecuredUiSuffix ( ) ) ; } } catch ( IOException e ) { throw new JspException ( e ) ; } return EVAL_PAGE ; }


Input: Populates the users that have been added . [CODESPLIT] @ Override protected void initUserDetailsService ( ) throws Exception { for ( UserDetailsBuilder userBuilder : userBuilders ) { getUserDetailsService ( ) . createUser ( userBuilder . build ( ) ) ; } for ( UserDetails userDetails : this . users ) { getUserDetailsService ( ) . createUser ( userDetails ) ; } }


Input: Allows adding a user to the { @link UserDetailsManager } that is being created . This method can be invoked multiple times to add multiple users . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public final C withUser ( User . UserBuilder userBuilder ) { this . users . add ( userBuilder . build ( ) ) ; return ( C ) this ; }


Input: Allows adding a user to the { @link UserDetailsManager } that is being created . This method can be invoked multiple times to add multiple users . [CODESPLIT] @ SuppressWarnings ( "unchecked" ) public final UserDetailsBuilder withUser ( String username ) { UserDetailsBuilder userBuilder = new UserDetailsBuilder ( ( C ) this ) ; userBuilder . username ( username ) ; this . userBuilders . add ( userBuilder ) ; return userBuilder ; }


Input: The default { [CODESPLIT] private SecurityWebFilterChain springSecurityFilterChain ( ServerHttpSecurity http ) { http . authorizeExchange ( ) . anyExchange ( ) . authenticated ( ) ; if ( isOAuth2Present && OAuth2ClasspathGuard . shouldConfigure ( this . context ) ) { OAuth2ClasspathGuard . configure ( this . context , http ) ; } else { http . httpBasic ( ) . and ( ) . formLogin ( ) ; } SecurityWebFilterChain result = http . build ( ) ; return result ; }


Input: Checks the value of an XML attribute which represents a redirect URL . If not empty or starting with $ ( potential placeholder ) or starting with # ( potential SpEL ) / or http it will raise an error . [CODESPLIT] static void validateHttpRedirect ( String url , ParserContext pc , Object source ) { if ( ! StringUtils . hasText ( url ) || UrlUtils . isValidRedirectUrl ( url ) || url . startsWith ( "$" ) || url . startsWith ( "#" ) ) { return ; } pc . getReaderContext ( ) . warning ( url + " is not a valid redirect URL (must start with '/' or http(s))" , source ) ; }


Input: Computes the <code > response< / code > portion of a Digest authentication header . Both the server and user agent should compute the <code > response< / code > independently . Provided as a static method to simplify the coding of user agents . [CODESPLIT] static String generateDigest ( boolean passwordAlreadyEncoded , String username , String realm , String password , String httpMethod , String uri , String qop , String nonce , String nc , String cnonce ) throws IllegalArgumentException { String a1Md5 ; String a2 = httpMethod + ":" + uri ; String a2Md5 = md5Hex ( a2 ) ; if ( passwordAlreadyEncoded ) { a1Md5 = password ; } else { a1Md5 = DigestAuthUtils . encodePasswordInA1Format ( username , realm , password ) ; } String digest ; if ( qop == null ) { // as per RFC 2069 compliant clients (also reaffirmed by RFC 2617) digest = a1Md5 + ":" + nonce + ":" + a2Md5 ; } else if ( "auth" . equals ( qop ) ) { // As per RFC 2617 compliant clients digest = a1Md5 + ":" + nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + a2Md5 ; } else { throw new IllegalArgumentException ( "This method does not support a qop: '" + qop + "'" ) ; } return md5Hex ( digest ) ; }


Input: Takes an array of <code > String< / code > s and for each element removes any instances of <code > removeCharacter< / code > and splits the element based on the <code > delimiter< / code > . A <code > Map< / code > is then generated with the left of the delimiter providing the key and the right of the delimiter providing the value . <p > Will trim both the key and value before adding to the <code > Map< / code > . < / p > [CODESPLIT] static Map < String , String > splitEachArrayElementAndCreateMap ( String [ ] array , String delimiter , String removeCharacters ) { if ( ( array == null ) || ( array . length == 0 ) ) { return null ; } Map < String , String > map = new HashMap <> ( ) ; for ( String s : array ) { String postRemove ; if ( removeCharacters == null ) { postRemove = s ; } else { postRemove = StringUtils . replace ( s , removeCharacters , "" ) ; } String [ ] splitThisArrayElement = split ( postRemove , delimiter ) ; if ( splitThisArrayElement == null ) { continue ; } map . put ( splitThisArrayElement [ 0 ] . trim ( ) , splitThisArrayElement [ 1 ] . trim ( ) ) ; } return map ; }


Input: Splits a <code > String< / code > at the first instance of the delimiter . <p > Does not include the delimiter in the response . < / p > [CODESPLIT] static String [ ] split ( String toSplit , String delimiter ) { Assert . hasLength ( toSplit , "Cannot split a null or empty string" ) ; Assert . hasLength ( delimiter , "Cannot use a null or empty delimiter to split a string" ) ; if ( delimiter . length ( ) != 1 ) { throw new IllegalArgumentException ( "Delimiter can only be one character in length" ) ; } int offset = toSplit . indexOf ( delimiter ) ; if ( offset < 0 ) { return null ; } String beforeDelimiter = toSplit . substring ( 0 , offset ) ; String afterDelimiter = toSplit . substring ( offset + 1 ) ; return new String [ ] { beforeDelimiter , afterDelimiter } ; }


Input: ======================================================================================================== [CODESPLIT] public void afterPropertiesSet ( ) throws Exception { Assert . notNull ( getSecureObjectClass ( ) , "Subclass must provide a non-null response to getSecureObjectClass()" ) ; Assert . notNull ( this . messages , "A message source must be set" ) ; Assert . notNull ( this . authenticationManager , "An AuthenticationManager is required" ) ; Assert . notNull ( this . accessDecisionManager , "An AccessDecisionManager is required" ) ; Assert . notNull ( this . runAsManager , "A RunAsManager is required" ) ; Assert . notNull ( this . obtainSecurityMetadataSource ( ) , "An SecurityMetadataSource is required" ) ; Assert . isTrue ( this . obtainSecurityMetadataSource ( ) . supports ( getSecureObjectClass ( ) ) , ( ) -> "SecurityMetadataSource does not support secure object class: " + getSecureObjectClass ( ) ) ; Assert . isTrue ( this . runAsManager . supports ( getSecureObjectClass ( ) ) , ( ) -> "RunAsManager does not support secure object class: " + getSecureObjectClass ( ) ) ; Assert . isTrue ( this . accessDecisionManager . supports ( getSecureObjectClass ( ) ) , ( ) -> "AccessDecisionManager does not support secure object class: " + getSecureObjectClass ( ) ) ; if ( this . afterInvocationManager != null ) { Assert . isTrue ( this . afterInvocationManager . supports ( getSecureObjectClass ( ) ) , ( ) -> "AfterInvocationManager does not support secure object class: " + getSecureObjectClass ( ) ) ; } if ( this . validateConfigAttributes ) { Collection < ConfigAttribute > attributeDefs = this . obtainSecurityMetadataSource ( ) . getAllConfigAttributes ( ) ; if ( attributeDefs == null ) { logger . warn ( "Could not validate configuration attributes as the SecurityMetadataSource did not return " + "any attributes from getAllConfigAttributes()" ) ; return ; } Set < ConfigAttribute > unsupportedAttrs = new HashSet <> ( ) ; for ( ConfigAttribute attr : attributeDefs ) { if ( ! this . runAsManager . supports ( attr ) && ! this . accessDecisionManager . supports ( attr ) && ( ( this . afterInvocationManager == null ) || ! this . afterInvocationManager . supports ( attr ) ) ) { unsupportedAttrs . add ( attr ) ; } } if ( unsupportedAttrs . size ( ) != 0 ) { throw new IllegalArgumentException ( "Unsupported configuration attributes: " + unsupportedAttrs ) ; } logger . debug ( "Validated configuration attributes" ) ; } }


Input: Cleans up the work of the <tt > AbstractSecurityInterceptor< / tt > after the secure object invocation has been completed . This method should be invoked after the secure object invocation and before afterInvocation regardless of the secure object invocation returning successfully ( i . e . it should be done in a finally block ) . [CODESPLIT] protected void finallyInvocation ( InterceptorStatusToken token ) { if ( token != null && token . isContextHolderRefreshRequired ( ) ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Reverting to original Authentication: " + token . getSecurityContext ( ) . getAuthentication ( ) ) ; } SecurityContextHolder . setContext ( token . getSecurityContext ( ) ) ; } }


Input: Completes the work of the <tt > AbstractSecurityInterceptor< / tt > after the secure object invocation has been completed . [CODESPLIT] protected Object afterInvocation ( InterceptorStatusToken token , Object returnedObject ) { if ( token == null ) { // public object return returnedObject ; } finallyInvocation ( token ) ; // continue to clean in this method for passivity if ( afterInvocationManager != null ) { // Attempt after invocation handling try { returnedObject = afterInvocationManager . decide ( token . getSecurityContext ( ) . getAuthentication ( ) , token . getSecureObject ( ) , token . getAttributes ( ) , returnedObject ) ; } catch ( AccessDeniedException accessDeniedException ) { AuthorizationFailureEvent event = new AuthorizationFailureEvent ( token . getSecureObject ( ) , token . getAttributes ( ) , token . getSecurityContext ( ) . getAuthentication ( ) , accessDeniedException ) ; publishEvent ( event ) ; throw accessDeniedException ; } } return returnedObject ; }


Input: Checks the current authentication token and passes it to the AuthenticationManager if { @link org . springframework . security . core . Authentication#isAuthenticated () } returns false or the property <tt > alwaysReauthenticate< / tt > has been set to true . [CODESPLIT] private Authentication authenticateIfRequired ( ) { Authentication authentication = SecurityContextHolder . getContext ( ) . getAuthentication ( ) ; if ( authentication . isAuthenticated ( ) && ! alwaysReauthenticate ) { if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Previously Authenticated: " + authentication ) ; } return authentication ; } authentication = authenticationManager . authenticate ( authentication ) ; // We don't authenticated.setAuthentication(true), because each provider should do // that if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Successfully Authenticated: " + authentication ) ; } SecurityContextHolder . getContext ( ) . setAuthentication ( authentication ) ; return authentication ; }


Input: Helper method which generates an exception containing the passed reason and publishes an event to the application context . <p > Always throws an exception . [CODESPLIT] private void credentialsNotFound ( String reason , Object secureObject , Collection < ConfigAttribute > configAttribs ) { AuthenticationCredentialsNotFoundException exception = new AuthenticationCredentialsNotFoundException ( reason ) ; AuthenticationCredentialsNotFoundEvent event = new AuthenticationCredentialsNotFoundEvent ( secureObject , configAttribs , exception ) ; publishEvent ( event ) ; throw exception ; }


Input: Obtains a user details service for use in RememberMeServices etc . Will return a caching version if available so should not be used for beans which need to separate the two . [CODESPLIT] private UserDetailsService getUserDetailsService ( ) { Map < String , ? > beans = getBeansOfType ( CachingUserDetailsService . class ) ; if ( beans . size ( ) == 0 ) { beans = getBeansOfType ( UserDetailsService . class ) ; } if ( beans . size ( ) == 0 ) { throw new ApplicationContextException ( "No UserDetailsService registered." ) ; } else if ( beans . size ( ) > 1 ) { throw new ApplicationContextException ( "More than one UserDetailsService registered. Please " + "use a specific Id reference in <remember-me/> <openid-login/> or <x509 /> elements." ) ; } return ( UserDetailsService ) beans . values ( ) . toArray ( ) [ 0 ] ; }


Input: Creates and adds additional PKCE parameters for use in the OAuth 2 . 0 Authorization and Access Token Requests [CODESPLIT] private void addPkceParameters ( Map < String , Object > attributes , Map < String , Object > additionalParameters ) { String codeVerifier = this . codeVerifierGenerator . generateKey ( ) ; attributes . put ( PkceParameterNames . CODE_VERIFIER , codeVerifier ) ; try { String codeChallenge = createCodeChallenge ( codeVerifier ) ; additionalParameters . put ( PkceParameterNames . CODE_CHALLENGE , codeChallenge ) ; additionalParameters . put ( PkceParameterNames . CODE_CHALLENGE_METHOD , "S256" ) ; } catch ( NoSuchAlgorithmException e ) { additionalParameters . put ( PkceParameterNames . CODE_CHALLENGE , codeVerifier ) ; } }


Input: ======================================================================================================== [CODESPLIT] @ Override protected final void successfulAuthentication ( HttpServletRequest request , HttpServletResponse response , FilterChain chain , Authentication authResult ) throws IOException , ServletException { boolean continueFilterChain = proxyTicketRequest ( serviceTicketRequest ( request , response ) , request ) ; if ( ! continueFilterChain ) { super . successfulAuthentication ( request , response , chain , authResult ) ; return ; } if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Authentication success. Updating SecurityContextHolder to contain: " + authResult ) ; } SecurityContextHolder . getContext ( ) . setAuthentication ( authResult ) ; // Fire event if ( this . eventPublisher != null ) { eventPublisher . publishEvent ( new InteractiveAuthenticationSuccessEvent ( authResult , this . getClass ( ) ) ) ; } chain . doFilter ( request , response ) ; }


Input: Overridden to provide proxying capabilities . [CODESPLIT] protected boolean requiresAuthentication ( final HttpServletRequest request , final HttpServletResponse response ) { final boolean serviceTicketRequest = serviceTicketRequest ( request , response ) ; final boolean result = serviceTicketRequest || proxyReceptorRequest ( request ) || ( proxyTicketRequest ( serviceTicketRequest , request ) ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "requiresAuthentication = " + result ) ; } return result ; }


Input: Indicates if the request is elgible to process a service ticket . This method exists for readability . [CODESPLIT] private boolean serviceTicketRequest ( final HttpServletRequest request , final HttpServletResponse response ) { boolean result = super . requiresAuthentication ( request , response ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "serviceTicketRequest = " + result ) ; } return result ; }


Input: Indicates if the request is elgible to process a proxy ticket . [CODESPLIT] private boolean proxyTicketRequest ( final boolean serviceTicketRequest , final HttpServletRequest request ) { if ( serviceTicketRequest ) { return false ; } final boolean result = authenticateAllArtifacts && obtainArtifact ( request ) != null && ! authenticated ( ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "proxyTicketRequest = " + result ) ; } return result ; }


Input: Determines if a user is already authenticated . [CODESPLIT] private boolean authenticated ( ) { Authentication authentication = SecurityContextHolder . getContext ( ) . getAuthentication ( ) ; return authentication != null && authentication . isAuthenticated ( ) && ! ( authentication instanceof AnonymousAuthenticationToken ) ; }


Input: Indicates if the request is elgible to be processed as the proxy receptor . [CODESPLIT] private boolean proxyReceptorRequest ( final HttpServletRequest request ) { final boolean result = proxyReceptorConfigured ( ) && proxyReceptorMatcher . matches ( request ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "proxyReceptorRequest = " + result ) ; } return result ; }


Input: Determines if the { @link CasAuthenticationFilter } is configured to handle the proxy receptor requests . [CODESPLIT] private boolean proxyReceptorConfigured ( ) { final boolean result = this . proxyGrantingTicketStorage != null && proxyReceptorMatcher != null ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "proxyReceptorConfigured = " + result ) ; } return result ; }


Input: Executes the SQL <tt > usersByUsernameQuery< / tt > and returns a list of UserDetails objects . There should normally only be one matching user . [CODESPLIT] protected List < UserDetails > loadUsersByUsername ( String username ) { return getJdbcTemplate ( ) . query ( getUsersByUsernameQuery ( ) , new String [ ] { username } , ( rs , rowNum ) -> { String userName = rs . getString ( 1 ) ; String password = rs . getString ( 2 ) ; boolean enabled = rs . getBoolean ( 3 ) ; boolean accLocked = false ; boolean accExpired = false ; boolean credsExpired = false ; if ( rs . getMetaData ( ) . getColumnCount ( ) > 3 ) { //NOTE: acc_locked, acc_expired and creds_expired are also to be loaded accLocked = rs . getBoolean ( 4 ) ; accExpired = rs . getBoolean ( 5 ) ; credsExpired = rs . getBoolean ( 6 ) ; } return new User ( userName , password , enabled , ! accExpired , ! credsExpired , ! accLocked , AuthorityUtils . NO_AUTHORITIES ) ; } ) ; }


Input: Find a unique { [CODESPLIT] public static WebApplicationContext findRequiredWebApplicationContext ( ServletContext servletContext ) { WebApplicationContext wac = _findWebApplicationContext ( servletContext ) ; if ( wac == null ) { throw new IllegalStateException ( "No WebApplicationContext found: no ContextLoaderListener registered?" ) ; } return wac ; }


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


Input: Uses a { [CODESPLIT] public StandardEvaluationContext createEvaluationContextInternal ( Authentication auth , MethodInvocation mi ) { return new MethodSecurityEvaluationContext ( auth , mi , getParameterNameDiscoverer ( ) ) ; }


Input: Creates the root object for expression evaluation . [CODESPLIT] protected MethodSecurityExpressionOperations createSecurityExpressionRoot ( Authentication authentication , MethodInvocation invocation ) { MethodSecurityExpressionRoot root = new MethodSecurityExpressionRoot ( authentication ) ; root . setThis ( invocation . getThis ( ) ) ; root . setPermissionEvaluator ( getPermissionEvaluator ( ) ) ; root . setTrustResolver ( getTrustResolver ( ) ) ; root . setRoleHierarchy ( getRoleHierarchy ( ) ) ; root . setDefaultRolePrefix ( getDefaultRolePrefix ( ) ) ; return root ; }


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


Input: Updates the cached JWK set from the configured URL . [CODESPLIT] private Mono < JWKSet > getJWKSet ( ) { return this . webClient . get ( ) . uri ( this . jwkSetURL ) . retrieve ( ) . bodyToMono ( String . class ) . map ( this :: parse ) . doOnNext ( jwkSet -> this . cachedJWKSet . set ( Mono . just ( jwkSet ) ) ) . cache ( ) ; }


Input: Returns the first specified key ID ( kid ) for a JWK matcher . [CODESPLIT] protected static String getFirstSpecifiedKeyID ( final JWKMatcher jwkMatcher ) { Set < String > keyIDs = jwkMatcher . getKeyIDs ( ) ; if ( keyIDs == null || keyIDs . isEmpty ( ) ) { return null ; } for ( String id : keyIDs ) { if ( id != null ) { return id ; } } return null ; // No kid in matcher }


Input: Redirects the response to the supplied URL . <p > If <tt > contextRelative< / tt > is set the redirect value will be the value after the request context path . Note that this will result in the loss of protocol information ( HTTP or HTTPS ) so will cause problems if a redirect is being performed to change to HTTPS for example . [CODESPLIT] public void sendRedirect ( HttpServletRequest request , HttpServletResponse response , String url ) throws IOException { String redirectUrl = calculateRedirectUrl ( request . getContextPath ( ) , url ) ; redirectUrl = response . encodeRedirectURL ( redirectUrl ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Redirecting to '" + redirectUrl + "'" ) ; } response . sendRedirect ( redirectUrl ) ; }


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


Input: Handles the creation of the final <tt > Authentication< / tt > object which will be returned by the provider . <p > The default implementation just creates a new OpenIDAuthenticationToken from the original but with the UserDetails as the principal and including the authorities loaded by the UserDetailsService . [CODESPLIT] protected Authentication createSuccessfulAuthentication ( UserDetails userDetails , OpenIDAuthenticationToken auth ) { return new OpenIDAuthenticationToken ( userDetails , this . authoritiesMapper . mapAuthorities ( userDetails . getAuthorities ( ) ) , auth . getIdentityUrl ( ) , auth . getAttributes ( ) ) ; }


Input: Votes according to JSR 250 . <p > If no JSR - 250 attributes are found it will abstain otherwise it will grant or deny access based on the attributes that are found . [CODESPLIT] public int vote ( Authentication authentication , Object object , Collection < ConfigAttribute > definition ) { boolean jsr250AttributeFound = false ; for ( ConfigAttribute attribute : definition ) { if ( Jsr250SecurityConfig . PERMIT_ALL_ATTRIBUTE . equals ( attribute ) ) { return ACCESS_GRANTED ; } if ( Jsr250SecurityConfig . DENY_ALL_ATTRIBUTE . equals ( attribute ) ) { return ACCESS_DENIED ; } if ( supports ( attribute ) ) { jsr250AttributeFound = true ; // Attempt to find a matching granted authority for ( GrantedAuthority authority : authentication . getAuthorities ( ) ) { if ( attribute . getAttribute ( ) . equals ( authority . getAuthority ( ) ) ) { return ACCESS_GRANTED ; } } } } return jsr250AttributeFound ? ACCESS_DENIED : ACCESS_ABSTAIN ; }


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


Input: Authentication has two phases . <ol > <li > The initial submission of the claimed OpenID . A redirect to the URL returned from the consumer will be performed and null will be returned . < / li > <li > The redirection from the OpenID server to the return_to URL once it has authenticated the user< / li > < / ol > [CODESPLIT] @ Override public Authentication attemptAuthentication ( HttpServletRequest request , HttpServletResponse response ) throws AuthenticationException , IOException { OpenIDAuthenticationToken token ; String identity = request . getParameter ( "openid.identity" ) ; if ( ! StringUtils . hasText ( identity ) ) { String claimedIdentity = obtainUsername ( request ) ; try { String returnToUrl = buildReturnToUrl ( request ) ; String realm = lookupRealm ( returnToUrl ) ; String openIdUrl = consumer . beginConsumption ( request , claimedIdentity , returnToUrl , realm ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "return_to is '" + returnToUrl + "', realm is '" + realm + "'" ) ; logger . debug ( "Redirecting to " + openIdUrl ) ; } response . sendRedirect ( openIdUrl ) ; // Indicate to parent class that authentication is continuing. return null ; } catch ( OpenIDConsumerException e ) { logger . debug ( "Failed to consume claimedIdentity: " + claimedIdentity , e ) ; throw new AuthenticationServiceException ( "Unable to process claimed identity '" + claimedIdentity + "'" ) ; } } if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Supplied OpenID identity is " + identity ) ; } try { token = consumer . endConsumption ( request ) ; } catch ( OpenIDConsumerException oice ) { throw new AuthenticationServiceException ( "Consumer error" , oice ) ; } token . setDetails ( authenticationDetailsSource . buildDetails ( request ) ) ; // delegate to the authentication provider Authentication authentication = this . getAuthenticationManager ( ) . authenticate ( token ) ; return authentication ; }


Input: Builds the <tt > return_to< / tt > URL that will be sent to the OpenID service provider . By default returns the URL of the current request . [CODESPLIT] protected String buildReturnToUrl ( HttpServletRequest request ) { StringBuffer sb = request . getRequestURL ( ) ; Iterator < String > iterator = returnToUrlParameters . iterator ( ) ; boolean isFirst = true ; while ( iterator . hasNext ( ) ) { String name = iterator . next ( ) ; // Assume for simplicity that there is only one value String value = request . getParameter ( name ) ; if ( value == null ) { continue ; } if ( isFirst ) { sb . append ( "?" ) ; isFirst = false ; } sb . append ( utf8UrlEncode ( name ) ) . append ( "=" ) . append ( utf8UrlEncode ( value ) ) ; if ( iterator . hasNext ( ) ) { sb . append ( "&" ) ; } } return sb . toString ( ) ; }


Input: Reads the <tt > claimedIdentityFieldName< / tt > from the submitted request . [CODESPLIT] protected String obtainUsername ( HttpServletRequest req ) { String claimedIdentity = req . getParameter ( claimedIdentityFieldName ) ; if ( ! StringUtils . hasText ( claimedIdentity ) ) { logger . error ( "No claimed identity supplied in authentication request" ) ; return "" ; } return claimedIdentity . trim ( ) ; }


Input: Performs URL encoding with UTF - 8 [CODESPLIT] private String utf8UrlEncode ( String value ) { try { return URLEncoder . encode ( value , "UTF-8" ) ; } catch ( UnsupportedEncodingException e ) { Error err = new AssertionError ( "The Java platform guarantees UTF-8 support, but it seemingly is not present." ) ; err . initCause ( e ) ; throw err ; } }


Input: ======================================================================================================== [CODESPLIT] public UserDetails getUserFromCache ( String username ) { Cache . ValueWrapper element = username != null ? cache . get ( username ) : null ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Cache hit: " + ( element != null ) + "; username: " + username ) ; } if ( element == null ) { return null ; } else { return ( UserDetails ) element . get ( ) ; } }


Input: Obtain the current active <code > Authentication< / code > [CODESPLIT] private Authentication getAuthentication ( ) { Authentication auth = SecurityContextHolder . getContext ( ) . getAuthentication ( ) ; if ( ! trustResolver . isAnonymous ( auth ) ) { return auth ; } return null ; }


Input: Returns the principal s name as obtained from the <code > SecurityContextHolder< / code > . Properly handles both <code > String< / code > - based and <code > UserDetails< / code > - based principals . [CODESPLIT] @ Override public String getRemoteUser ( ) { Authentication auth = getAuthentication ( ) ; if ( ( auth == null ) || ( auth . getPrincipal ( ) == null ) ) { return null ; } if ( auth . getPrincipal ( ) instanceof UserDetails ) { return ( ( UserDetails ) auth . getPrincipal ( ) ) . getUsername ( ) ; } return auth . getPrincipal ( ) . toString ( ) ; }


Input: Returns the <code > Authentication< / code > ( which is a subclass of <code > Principal< / code > ) or <code > null< / code > if unavailable . [CODESPLIT] @ Override public Principal getUserPrincipal ( ) { Authentication auth = getAuthentication ( ) ; if ( ( auth == null ) || ( auth . getPrincipal ( ) == null ) ) { return null ; } return auth ; }


Input: Gets the { @link LdapAuthoritiesPopulator } and defaults to { @link DefaultLdapAuthoritiesPopulator } [CODESPLIT] private LdapAuthoritiesPopulator getLdapAuthoritiesPopulator ( ) { if ( ldapAuthoritiesPopulator != null ) { return ldapAuthoritiesPopulator ; } DefaultLdapAuthoritiesPopulator defaultAuthoritiesPopulator = new DefaultLdapAuthoritiesPopulator ( contextSource , groupSearchBase ) ; defaultAuthoritiesPopulator . setGroupRoleAttribute ( groupRoleAttribute ) ; defaultAuthoritiesPopulator . setGroupSearchFilter ( groupSearchFilter ) ; defaultAuthoritiesPopulator . setRolePrefix ( this . rolePrefix ) ; this . ldapAuthoritiesPopulator = defaultAuthoritiesPopulator ; return defaultAuthoritiesPopulator ; }


Input: Gets the { @link GrantedAuthoritiesMapper } and defaults to { @link SimpleAuthorityMapper } . [CODESPLIT] protected GrantedAuthoritiesMapper getAuthoritiesMapper ( ) throws Exception { if ( authoritiesMapper != null ) { return authoritiesMapper ; } SimpleAuthorityMapper simpleAuthorityMapper = new SimpleAuthorityMapper ( ) ; simpleAuthorityMapper . setPrefix ( this . rolePrefix ) ; simpleAuthorityMapper . afterPropertiesSet ( ) ; this . authoritiesMapper = simpleAuthorityMapper ; return simpleAuthorityMapper ; }


Input: Creates the { @link LdapAuthenticator } to use [CODESPLIT] private LdapAuthenticator createLdapAuthenticator ( BaseLdapPathContextSource contextSource ) { AbstractLdapAuthenticator ldapAuthenticator = passwordEncoder == null ? createBindAuthenticator ( contextSource ) : createPasswordCompareAuthenticator ( contextSource ) ; LdapUserSearch userSearch = createUserSearch ( ) ; if ( userSearch != null ) { ldapAuthenticator . setUserSearch ( userSearch ) ; } if ( userDnPatterns != null && userDnPatterns . length > 0 ) { ldapAuthenticator . setUserDnPatterns ( userDnPatterns ) ; } return postProcess ( ldapAuthenticator ) ; }


Input: Creates { @link PasswordComparisonAuthenticator } [CODESPLIT] private PasswordComparisonAuthenticator createPasswordCompareAuthenticator ( BaseLdapPathContextSource contextSource ) { PasswordComparisonAuthenticator ldapAuthenticator = new PasswordComparisonAuthenticator ( contextSource ) ; if ( passwordAttribute != null ) { ldapAuthenticator . setPasswordAttributeName ( passwordAttribute ) ; } ldapAuthenticator . setPasswordEncoder ( passwordEncoder ) ; return ldapAuthenticator ; }


Input: Specifies the { @link org . springframework . security . crypto . password . PasswordEncoder } to be used when authenticating with password comparison . [CODESPLIT] public LdapAuthenticationProviderConfigurer < B > passwordEncoder ( final org . springframework . security . crypto . password . PasswordEncoder passwordEncoder ) { Assert . notNull ( passwordEncoder , "passwordEncoder must not be null." ) ; this . passwordEncoder = passwordEncoder ; return this ; }


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


Input: { [CODESPLIT] @ Override public Mono < Void > onLogoutSuccess ( WebFilterExchange exchange , Authentication authentication ) { return Mono . just ( authentication ) . filter ( OAuth2AuthenticationToken . class :: isInstance ) . filter ( token -> authentication . getPrincipal ( ) instanceof OidcUser ) . map ( OAuth2AuthenticationToken . class :: cast ) . flatMap ( this :: endSessionEndpoint ) . map ( endSessionEndpoint -> endpointUri ( endSessionEndpoint , authentication ) ) . switchIfEmpty ( this . serverLogoutSuccessHandler . onLogoutSuccess ( exchange , authentication ) . then ( Mono . empty ( ) ) ) . flatMap ( endpointUri -> this . redirectStrategy . sendRedirect ( exchange . getExchange ( ) , endpointUri ) ) ; }


Input: ======================================================================================================== [CODESPLIT] public void commence ( HttpServletRequest request , HttpServletResponse response ) throws IOException , ServletException { String queryString = request . getQueryString ( ) ; String redirectUrl = request . getRequestURI ( ) + ( ( queryString == null ) ? "" : ( "?" + queryString ) ) ; Integer currentPort = Integer . valueOf ( portResolver . getServerPort ( request ) ) ; Integer redirectPort = getMappedPort ( currentPort ) ; if ( redirectPort != null ) { boolean includePort = redirectPort . intValue ( ) != standardPort ; redirectUrl = scheme + request . getServerName ( ) + ( ( includePort ) ? ( ":" + redirectPort ) : "" ) + redirectUrl ; } if ( logger . isDebugEnabled ( ) ) { logger . debug ( "Redirecting to: " + redirectUrl ) ; } redirectStrategy . sendRedirect ( request , response , redirectUrl ) ; }


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


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


Input: Get a list of Granted Authorities based on the current user s WebSphere groups . [CODESPLIT] private Collection < ? extends GrantedAuthority > getWebSphereGroupsBasedGrantedAuthorities ( ) { List < String > webSphereGroups = wasHelper . getGroupsForCurrentUser ( ) ; Collection < ? extends GrantedAuthority > userGas = webSphereGroups2GrantedAuthoritiesMapper . getGrantedAuthorities ( webSphereGroups ) ; if ( logger . isDebugEnabled ( ) ) { logger . debug ( "WebSphere groups: " + webSphereGroups + " mapped to Granted Authorities: " + userGas ) ; } return userGas ; }


Input: Creates an instance of PasswordPolicyResponseControl if the passed control is a response control of this type . Attributes of the result are filled with the correct values ( e . g . error code ) . [CODESPLIT] public Control getControlInstance ( Control ctl ) { if ( ctl . getID ( ) . equals ( PasswordPolicyControl . OID ) ) { return new PasswordPolicyResponseControl ( ctl . getEncodedValue ( ) ) ; } return null ; }


Input: ======================================================================================================== [CODESPLIT] public void afterPropertiesSet ( ) throws Exception { Assert . notNull ( this . authenticationUserDetailsService , "An authenticationUserDetailsService must be set" ) ; Assert . notNull ( this . ticketValidator , "A ticketValidator must be set" ) ; Assert . notNull ( this . statelessTicketCache , "A statelessTicketCache must be set" ) ; Assert . hasText ( this . key , "A Key is required so CasAuthenticationProvider can identify tokens it previously authenticated" ) ; Assert . notNull ( this . messages , "A message source must be set" ) ; }