下面列出了怎么用org.springframework.security.authentication.AuthenticationProvider的API类实例代码及写法,或者点击链接到github查看源代码。
public static void main(String[] args) {
// 初始化密码认证处理器
PasswordEncoder passwordEncoder = new MyMessageDigestPasswordEncoder("md5");
// 初始化认证服务
UserDetailsService userDetailsService = new MyUserDetailsService();
// 初始化认证提供者
AuthenticationProvider provider = new MyAuthenticationProvider(userDetailsService, passwordEncoder);
List<AuthenticationProvider> providers = new ArrayList<>();
providers.add(provider);
// 初始化认证管理器
AuthenticationManager am = new MyAuthenticationManager(providers);
MyUsernamePasswordAuthenticationFilter filter = new MyUsernamePasswordAuthenticationFilter("/login");
filter.setAuthenticationManager(am);
//filter.doFilter(req, res, chain);
}
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
Class<? extends Authentication> toTest = authentication.getClass();
Authentication result = null;
for (AuthenticationProvider provider : providers) {
if (!provider.supports(toTest)) {
continue;
}
// 调用认证提供者进行认证,如果 result 不为 null ,说明认证通过
result = provider.authenticate(authentication);
if (result != null) {
break;
}
}
if (result == null) {
throw new ProviderNotFoundException("ProviderManager.providerNotFound");
}
return result;
}
/**
* Initializes an AuthenticationManager if authentication has been enabled.
*
* @return AuthenticationManager
*/
@Bean
@ConditionalOnProperty(prefix = "feast.security.authentication", name = "enabled")
AuthenticationManager authenticationManager() {
final List<AuthenticationProvider> providers = new ArrayList<>();
if (securityProperties.getAuthentication().isEnabled()) {
switch (securityProperties.getAuthentication().getProvider()) {
case "jwt":
providers.add(
new DefaultJwtAuthenticationProvider(
securityProperties.getAuthentication().getOptions()));
break;
default:
throw new IllegalArgumentException(
"Please configure an Authentication Provider if you have enabled authentication.");
}
}
return new ProviderManager(providers);
}
public List<String> getRealms() {
List<AuthenticationProvider> providers = authenticationManager.getProviders();
if (LOG.isDebugEnabled()) {
LOG.debug("Found " + providers.size() + " authentication providers");
}
List<String> realms = new ArrayList<String>();
for (AuthenticationProvider provider : providers) {
if (provider instanceof ExternalAuthenticationProvider) {
ExternalAuthenticationProvider externalProvider = (ExternalAuthenticationProvider) provider;
realms.add(externalProvider.getRealm());
} else if (provider instanceof NextServerAuthenticationProvider) {
realms.add(""); // default provider
}
}
return realms;
}
private AuthenticationProvider communityAuthenticationProvider() {
final Role user = new Role.Builder()
.setName(FindCommunityRole.USER.value())
.setPrivileges(Collections.singleton("login"))
.build();
final Set<String> defaultRoles;
if (defaultRolesProperty.isEmpty()) {
defaultRoles = Collections.emptySet();
} else {
defaultRoles = new HashSet<>(Arrays.asList(defaultRolesProperty.split(",")));
}
return new CommunityAuthenticationProvider(
configService,
userService,
new Roles(Collections.singletonList(user)),
Collections.singleton("login"),
grantedAuthoritiesMapper,
defaultRoles
);
}
public OtpGeneratingAuthenticationProvider(AuthenticationProvider provider,
Tokenstore tokenstore, LookupStrategy lookupStrategy, SendStrategy sendStrategy) {
if (provider == null) {
throw new IllegalArgumentException("Embedded authentication provider must not be null.");
}
if (tokenstore == null) {
throw new IllegalArgumentException("Tokenstore must not be null.");
}
if (lookupStrategy == null) {
throw new IllegalArgumentException("LookupStrategy must not be null.");
}
if (sendStrategy == null) {
throw new IllegalArgumentException("SendStrategy must not be null.");
}
this.provider = provider;
this.tokenstore = tokenstore;
this.lookupStrategy = lookupStrategy;
this.sendStrategy = sendStrategy;
this.gen = new DefaultOtpGenerator(DEFAULT_OTP_LENGTH);
}
@Bean("daoAuthenticationProvider")
protected AuthenticationProvider daoAuthenticationProvider() throws Exception{
DaoAuthenticationProvider daoProvider = new DaoAuthenticationProvider();
daoProvider.setPasswordEncoder(passwordEncoder());
daoProvider.setUserDetailsService(userInfoService());
return daoProvider;
}
@Bean
public AuthenticationProvider authenticationProviderBean() {
DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
authenticationProvider.setPasswordEncoder(passwordEncoder);
authenticationProvider.setUserDetailsService(userDetailsService());
return authenticationProvider;
}
@Autowired
public InceptionSecurity(PasswordEncoder aPasswordEncoder,
@Lazy AuthenticationManager aAuthenticationManager,
@Lazy AuthenticationProvider aAuthenticationProvider, DataSource aDataSource,
UserDao aUserRepository)
{
passwordEncoder = aPasswordEncoder;
authenticationManager = aAuthenticationManager;
authenticationProvider = aAuthenticationProvider;
dataSource = aDataSource;
userRepository = aUserRepository;
}
@Test
public void shouldCreateRS256ConfigurerWithCustomAuthenticationProvider() throws Exception {
AuthenticationProvider provider = mock(AuthenticationProvider.class);
JwtWebSecurityConfigurer configurer = JwtWebSecurityConfigurer.forRS256("audience", "issuer", provider);
assertThat(configurer, is(notNullValue()));
assertThat(configurer.audience, is("audience"));
assertThat(configurer.issuers, arrayWithSize(1));
assertThat(configurer.issuers, arrayContaining("issuer"));
assertThat(configurer.provider, is(notNullValue()));
assertThat(configurer.provider, is(provider));
}
@Test
public void shouldCreateHS256ConfigurerWithCustomAuthenticationProvider() throws Exception {
AuthenticationProvider provider = mock(AuthenticationProvider.class);
JwtWebSecurityConfigurer configurer = JwtWebSecurityConfigurer.forHS256("audience", "issuer", provider);
assertThat(configurer, is(notNullValue()));
assertThat(configurer.audience, is("audience"));
assertThat(configurer.issuers, arrayWithSize(1));
assertThat(configurer.issuers, arrayContaining("issuer"));
assertThat(configurer.provider, is(notNullValue()));
assertThat(configurer.provider, is(provider));
}
/**
* Authentication provider which provides the logged in user's credentials for
* verification and authentication if they are coeect
*
* @return
*/
public AuthenticationProvider authProvider() {
// The custom authentication provider defined for this app
CustomUserDetailsAuthenticationProvider provider = new CustomUserDetailsAuthenticationProvider(
passwordEncoder(), userDetailsService);
return provider;
}
@Bean(name = "dbAuthenticationProvider")
public AuthenticationProvider dbAuthenticationProvider() {
CustomDaoAuthenticationProvider daoAuthenticationProvider = new CustomDaoAuthenticationProvider();
daoAuthenticationProvider.setUserDetailsService(userDetailsService());
daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
return daoAuthenticationProvider;
}
@Bean
/*
* Add the authentication providers to the manager.
*/
AuthenticationManager authenticationManager() {
final List<AuthenticationProvider> providers = new ArrayList<>();
providers.add(jwtAuthenticationProvider());
return new ProviderManager(providers);
}
@Bean
AuthenticationManager authenticationManager() {
final List<AuthenticationProvider> providers = new ArrayList<>();
providers.add(daoAuthenticationProvider());
// providers.add(anonymousAuthenticationProvider());
return new ProviderManager(providers);
}
@Bean
public AuthenticationProvider daoAuthenticationProvider() {
DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
provider.setPasswordEncoder(passwordEncoder());
provider.setUserDetailsPasswordService(this.databaseUserDetailPasswordService);
provider.setUserDetailsService(this.databaseUserDetailsService);
return provider;
}
@Bean
public AuthenticationProvider authenticationProvider(){
ActiveDirectoryLdapAuthenticationProvider ap = new ActiveDirectoryLdapAuthenticationProvider(
"corp.jbcpcalendar.com",
"ldap://corp.jbcpcalendar.com/");
ap.setConvertSubErrorCodesToExceptions(true);
return ap;
}
private PasswordAuthenticator authProviderAuthenticator(Auth authProps) throws IllegalArgumentException {
try {
AuthenticationProvider authProvider = Objects.isNull(authProps.getAuthProviderBeanName())
? appContext.getBean(AuthenticationProvider.class)
: appContext.getBean(authProps.getAuthProviderBeanName(), AuthenticationProvider.class);
return new AuthProviderSshdPasswordAuthenticator(authProvider);
} catch (BeansException ex) {
throw new IllegalArgumentException("Expected a default or valid AuthenticationProvider bean", ex);
}
}
@Bean
// Add the authentication providers to the manager.
AuthenticationManager authenticationManager() {
final List<AuthenticationProvider> providers = new ArrayList<>();
providers.add(daoAuthenticationProvider());
return new ProviderManager(providers);
}
@Bean
AuthenticationManager authenticationManager() {
final List<AuthenticationProvider> providers = new ArrayList<>();
providers.add(daoAuthenticationProvider());
// providers.add(anonymousAuthenticationProvider());
return new ProviderManager(providers);
}
@Bean(name = "dbAuthenticationProvider")
@ConditionalOnMissingBean(AuthenticationProvider.class)
@ConditionalOnProperty(prefix = "flowable.idm.ldap", name = "enabled", havingValue = "false", matchIfMissing = true)
public AuthenticationProvider dbAuthenticationProvider(PasswordEncoder passwordEncoder, UserDetailsService userDetailsService) {
CustomDaoAuthenticationProvider daoAuthenticationProvider = new CustomDaoAuthenticationProvider();
daoAuthenticationProvider.setUserDetailsService(userDetailsService);
daoAuthenticationProvider.setPasswordEncoder(passwordEncoder);
return daoAuthenticationProvider;
}
@Override
public Collection<AuthenticationProvider> getAuthenticationProviders() {
return Collections.singleton(new IdolPreAuthenticatedAuthenticationProvider(
userService,
grantedAuthoritiesMapper,
Arrays.stream(preAuthenticatedRoles.split(","))
.map(FindCommunityRole::fromValue)
.map(FindCommunityRole::value)
.collect(Collectors.toSet())
));
}
@Bean(name = "preAuthAuthenticationManager")
public AuthenticationManager preAuthAuthenticationManager() {
PreAuthenticatedAuthenticationProvider preAuthProvider = new PreAuthenticatedAuthenticationProvider();
preAuthProvider.setPreAuthenticatedUserDetailsService(preAuthUserDetailsService);
List<AuthenticationProvider> providers = new ArrayList<AuthenticationProvider>();
providers.add(preAuthProvider);
return new ProviderManager(providers);
}
@Test
public void testDefaultRoles() {
final Collection<AuthenticationProvider> authenticationProviders = idolSecurityCustomizer.getAuthenticationProviders();
assertThat(authenticationProviders, hasSize(1));
final Authentication authentication = authenticationProviders.stream()
.findFirst()
.map(authenticationProvider -> authenticationProvider.authenticate(this.foreignAuthentication))
.orElseThrow(() -> new AssertionError("AuthenticationProvider did not authenticate"));
assertThat(authentication.getAuthorities(), contains(authority("FindUser")));
}
@Autowired
public WebAnnoSecurity(PasswordEncoder aPasswordEncoder,
@Lazy AuthenticationManager aAuthenticationManager,
@Lazy AuthenticationProvider aAuthenticationProvider, DataSource aDataSource,
UserDao aUserRepository)
{
passwordEncoder = aPasswordEncoder;
authenticationManager = aAuthenticationManager;
authenticationProvider = aAuthenticationProvider;
dataSource = aDataSource;
userRepository = aUserRepository;
}
@Bean
@Override
protected AuthenticationManager authenticationManager() throws Exception {
List<AuthenticationProvider> providers = new ArrayList<>(1);
providers.add(preAuthAuthProvider());
return new ProviderManager(providers);
}
@Bean
public AuthenticationProvider authenticationProvider(UserDetailsService userDetailsService, PasswordEncoder passwordEncoder) {
DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
daoAuthenticationProvider.setUserDetailsService(userDetailsService);
daoAuthenticationProvider.setPasswordEncoder(passwordEncoder);
daoAuthenticationProvider.setHideUserNotFoundExceptions(false);
return daoAuthenticationProvider;
}
@Bean(name = "authenticationProvider")
public AuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider result = new DaoAuthenticationProvider();
result.setUserDetailsService(inMemoryUserDetailsManager());
return result;
}
@Bean
public AuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
daoAuthenticationProvider.setUserDetailsService(userService);
daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
return daoAuthenticationProvider;
}
@Bean
public AuthenticationProvider tokenAuthenticationProvider() {
return new TokenAuthenticationProvider();
}