Как определить пользовательский поставщик аутентификации с помощью Spring Безопасность с конфигурациями Java? Я хотел бы выполнить учетные данные для проверки входа в моей собственной базе данных.
Пользовательский поставщик аутентификации с Spring Безопасность и настройка Java
Ответ 1
Следующее делает то, что вам нужно (CustomAuthenticationProvider
- это ваша реализация, которой необходимо управлять с помощью Spring)
@Configuration
@EnableWebMvcSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CustomAuthenticationProvider customAuthenticationProvider;
@Override
protected void configure(HttpSecurity http) throws Exception {
/**
* Do your stuff here
*/
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(customAuthenticationProvider);
}
}
Ответ 2
Как показано на baeldung.com, определите поставщика проверки подлинности следующим образом:
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
@Override
public Authentication authenticate(Authentication authentication)
throws AuthenticationException {
String name = authentication.getName();
String password = authentication.getCredentials().toString();
if (shouldAuthenticateAgainstThirdPartySystem(username, password)) {
// use the credentials
// and authenticate against the third-party system
return new UsernamePasswordAuthenticationToken(
name, password, new ArrayList<>());
} else {
return null;
}
}
@Override
public boolean supports(Class<?> authentication) {
return authentication.equals(
UsernamePasswordAuthenticationToken.class);
}
}
и следующий код соответствует java config:
@Configuration
@EnableWebSecurity
@ComponentScan("org.project.security")
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CustomAuthenticationProvider authProvider;
@Override
protected void configure(
AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authProvider);
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated()
.and()
.httpBasic();
}
}