Пользовательский провайдер аутентификации с Spring Security и Java Config

Как я могу определить настраиваемого поставщика аутентификации с помощью Spring Security с конфигурациями Java? Я хочу выполнить проверку учетных данных для входа в мою собственную базу данных.


person vdenotaris    schedule 24.03.2014    source источник
comment
Документация по безопасности spring дает вам всю необходимую информацию - как настроить XML и конечные точки вашей конфигурации. кроме того, вам придется поддерживать такие процессы, как создание учетной записи, забытый пароль и т. д., которые вы можете использовать с открытым исходным кодом: github.com/OhadR/oAuth2-sample/tree/master/authentication-flows   -  person OhadR    schedule 24.03.2014


Ответы (2)


Следующее делает то, что вам нужно (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);
    }
}
person geoand    schedule 24.03.2014
comment
Можно ли зарегистрировать собственного поставщика аутентификации в дополнение к существующим? - person Display name; 10.06.2016
comment
@Seppl Я не думаю, что что-то подобное существует из коробки (хотя я легко могу ошибиться), но я почти уверен, что что-то подобное можно было бы реализовать относительно легко. Посмотрите это - person geoand; 10.06.2016
comment
Согласно Spring Docu, auth.authenticationProvider() добавит аутентификацию на основе переданного настраиваемого AuthenticationProvider. Я предполагаю, что таким образом вы получите стек провайдеров. - person Christoph Grimmer-Dietrich; 20.09.2017

Как показано на 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:

@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();
    }
}
person M2E67    schedule 15.02.2017
comment
Вы только что скопировали это прямо с baeldung.com/spring-security-authentication-provider. Хотя ответ, безусловно, полезен, также необходимо указать источники. - person moritz; 07.08.2017