View Javadoc
1   package cn.home1.oss.lib.security;
2   
3   import com.google.common.base.Preconditions;
4   import com.google.common.collect.ImmutableList;
5   
6   import org.springframework.security.authentication.AuthenticationProvider;
7   import org.springframework.security.core.Authentication;
8   import org.springframework.security.core.AuthenticationException;
9   
10  import java.util.List;
11  import java.util.Optional;
12  
13  /**
14   * Created by zhanghaolun on 16/7/6.
15   */
16  public class CompositeAuthenticationProvider implements AuthenticationProvider {
17  
18    private List<AuthenticationProvider> delegates = ImmutableList.of();
19  
20    public void setDelegates(final List<AuthenticationProvider> delegates) {
21      Preconditions.checkArgument(delegates != null, "delegates must not null");
22      this.delegates = delegates;
23    }
24  
25    AuthenticationProvider findAuthenticationProviderFor(final Authentication authentication) {
26      return authentication != null ? this.findAuthenticationProviderFor(authentication.getClass()) : null;
27    }
28  
29    AuthenticationProvider findAuthenticationProviderFor(final Class<?> authentication) {
30      final AuthenticationProvider found;
31      if (authentication != null) {
32        final Optional<AuthenticationProvider> optional =
33          this.delegates.stream().filter(provider -> provider.supports(authentication)).findFirst();
34        found = optional.isPresent() ? optional.get() : null;
35      } else {
36        found = null;
37      }
38      return found;
39    }
40  
41    @Override
42    public Authentication authenticate(final Authentication authentication) throws AuthenticationException {
43      final AuthenticationProvider authenticationProvider = this.findAuthenticationProviderFor(authentication);
44      return authenticationProvider != null ? authenticationProvider.authenticate(authentication) : null;
45    }
46  
47    @Override
48    public boolean supports(final Class<?> authentication) {
49      return this.findAuthenticationProviderFor(authentication) != null;
50    }
51  }