Пользовательский AuthenticationProvider не вызывается - PullRequest
0 голосов
/ 28 февраля 2020

Я занимаюсь разработкой приложения с загрузочной пружиной 2. Я пытаюсь реализовать Spring Spring для этого. Я использовал для этого пользовательский AutenticationProvider. Но он не вызывается. Однако проверка подлинности источника работает. Пожалуйста, помогите мне решить эту проблему. Я пробовал много способов, но это не сработало. Я использую jwt для создания токенов.

Класс реализации WebSecurityConfigurerAdapter

@Configuration
    @EnableGlobalMethodSecurity(prePostEnabled = true)
@ComponentScan
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private JwtAuthenticationEntryPoint unauthorizedHandler;
@Autowired
private SecurmailSecurityProvider provider;
@Override
protected void configure(AuthenticationManagerBuilder authentication) throws Exception {
    authentication.authenticationProvider( getKBServicesAuthenticationProvider());
}
@Bean
protected AuthenticationProvider getKBServicesAuthenticationProvider() {
    return new SecurmailSecurityProvider();
}
@Bean
public JwtAuthenticationFilter authenticationTokenFilterBean() throws Exception {
    return new JwtAuthenticationFilter();
}
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors().and().csrf().disable().
    authenticationProvider(provider).
    authorizeRequests()
    .antMatchers(MessageController.URL_AUTHENTICATE).permitAll()
    .anyRequest().authenticated()
    .and()
    .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()
    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    http
    .addFilterBefore(authenticationTokenFilterBean(), SecurityContextHolderAwareRequestFilter.class);
    http.headers().frameOptions().disable();
}

Класс провайдера пользовательской аутентификации

    @Component
@Primary
public class SecurmailSecurityProvider implements AuthenticationProvider {

@Autowired
MessageClientRepository clientRepo;

@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {

    if (authentication.isAuthenticated()) return authentication;

    SmAuthenticationToken token = (SmAuthenticationToken) authentication;

    if (token.getGuid() != null && !token.getGuid().trim().isEmpty()) {
        MessageClient client = clientRepo.findByGuid(token.getGuid());
        if (client != null) {               
            return new SmAuthenticationToken(client);
    }


}
    return null;
}
@Override
public boolean supports(Class<?> authentication) {
    return (SmAuthenticationToken.class.isAssignableFrom(authentication));

}

1 Ответ

0 голосов
/ 28 февраля 2020

Уже вы автоматически подключили провайдера CustomAuthentication с помощью

@Autowired
private SecurmailSecurityProvider provider;

, снова создавая компонент и передавая провайдеру CustomAuthentication

@Bean
protected AuthenticationProvider getKBServicesAuthenticationProvider() {
    return new SecurmailSecurityProvider();
}

Вместо кода ниже

@Autowired
private SecurmailSecurityProvider provider;
@Override
protected void configure(AuthenticationManagerBuilder authentication) throws Exception {
    authentication.authenticationProvider( getKBServicesAuthenticationProvider());
}
@Bean
protected AuthenticationProvider getKBServicesAuthenticationProvider() {
    return new SecurmailSecurityProvider();
}

Используйте этот код

@Autowired
private SecurmailSecurityProvider provider;

@Override
protected void configure(AuthenticationManagerBuilder authentication) throws Exception {
    authentication.authenticationProvider(provider);
}

А также реализация поставщика нестандартной аутентификации должна быть такой, как показано ниже:

@Component
public class SecurmailSecurityProvider implements AuthenticationProvider {

    @Override
    public Authentication authenticate(Authentication authentication) 
      throws AuthenticationException {

        String name = authentication.getName();
        String password = authentication.getCredentials().toString();

        if (shouldAuthenticateAgainstThirdPartySystem()) {

            // 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);
    }
}
...