Безопасность Springboot + jwt 'springSecurityFilterChain' ошибка - PullRequest
0 голосов
/ 11 июня 2018

Я получил ошибку в своем коде Springboot.
Но я не могу знать, почему это с ошибкой и не работает.

Я использовал Jpa.и это работало хорошо
(как и прежде, чем использовать безопасность и Oauth, jwt)
я добавил фильтр в @ Configuration.

журналы здесь

    org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.NoSuchMethodError: org.springframework.security.authentication.dao.DaoAuthenticationProvider.setPasswordEncoder(Lorg/springframework/security/crypto/password/PasswordEncoder;)V
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:587)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1254)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1103)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:541)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:501)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:304)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:760)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:869)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550)
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140)
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759)
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:395)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:327)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1255)
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1243)
    at kr.avansoft.demo.TokenServerTestV3Application.main(TokenServerTestV3Application.java:20)
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.NoSuchMethodError: org.springframework.security.authentication.dao.DaoAuthenticationProvider.setPasswordEncoder(Lorg/springframework/security/crypto/password/PasswordEncoder;)V
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185)
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:579)
    ... 20 common frames omitted
Caused by: java.lang.NoSuchMethodError: org.springframework.security.authentication.dao.DaoAuthenticationProvider.setPasswordEncoder(Lorg/springframework/security/crypto/password/PasswordEncoder;)V
    at org.springframework.security.config.annotation.authentication.configurers.userdetails.AbstractDaoAuthenticationConfigurer.passwordEncoder(AbstractDaoAuthenticationConfigurer.java:72)
    at org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter$DefaultPasswordEncoderAuthenticationManagerBuilder.userDetailsService(WebSecurityConfigurerAdapter.java:573)
    at org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer.init(AuthorizationServerSecurityConfigurer.java:137)
    at org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer.init(AuthorizationServerSecurityConfigurer.java:55)
    at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.init(AbstractConfiguredSecurityBuilder.java:371)
    at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.doBuild(AbstractConfiguredSecurityBuilder.java:325)
    at org.springframework.security.config.annotation.AbstractSecurityBuilder.build(AbstractSecurityBuilder.java:41)
    at org.springframework.security.config.annotation.web.builders.WebSecurity.performBuild(WebSecurity.java:292)
    at org.springframework.security.config.annotation.web.builders.WebSecurity.performBuild(WebSecurity.java:79)
    at org.springframework.security.config.annotation.AbstractConfiguredSecurityBuilder.doBuild(AbstractConfiguredSecurityBuilder.java:334)
    at org.springframework.security.config.annotation.AbstractSecurityBuilder.build(AbstractSecurityBuilder.java:41)
    at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration.springSecurityFilterChain(WebSecurityConfiguration.java:104)
    at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$2e1380d3.CGLIB$springSecurityFilterChain$3(<generated>)
    at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$2e1380d3$$FastClassBySpringCGLIB$$4dfe46c7.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:228)
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:361)
    at org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration$$EnhancerBySpringCGLIB$$2e1380d3.springSecurityFilterChain(<generated>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154)
    ... 21 common frames omitted

мой файл SecurityConfig

@Configuration
@EnableWebSecurity
@EnableJpaRepositories(basePackages= {"kr.avansoft.bean.repository"})
public class SecurityConfig extends WebSecurityConfigurerAdapter{

    @Bean
    public DaoAuthenticationProvider daoAuthenticationProvider() {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setUserDetailsService(userDetailService);
        provider.setPasswordEncoder(shaPasswordEncoder);
        return provider; 
    }

    @Override
    @Bean(name=BeanIds.AUTHENTICATION_MANAGER)
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    public 

    @Autowired
    SHAPasswordEncoder shaPasswordEncoder;

    @Autowired
    UserDetailsService userDetailService;

    @Autowired
    DaoAuthenticationProvider daoAuthenticationProvider; 

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(daoAuthenticationProvider);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(daoAuthenticationProvider);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authenticationProvider(daoAuthenticationProvider)
            .authorizeRequests()
            .antMatchers("/admin/**").hasRole("ADMIN")
            .antMatchers("/**").permitAll()
            .and().formLogin()
            .loginProcessingUrl("/login")
            .defaultSuccessUrl("/")
        .failureUrl("/login")
        .and()
        .logout();
    }

}

@Configuration
@EnableWebSecurity
@EnableJpaRepositories(basePackages= {"kr.avansoft.bean.repository"})
public class SecurityConfig extends WebSecurityConfigurerAdapter{

    @Bean
    public DaoAuthenticationProvider daoAuthenticationProvider() {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setUserDetailsService(userDetailService);
        provider.setPasswordEncoder(shaPasswordEncoder);
        return provider; 
    }

    @Override
    @Bean(name=BeanIds.AUTHENTICATION_MANAGER)
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    public 

    @Autowired
    SHAPasswordEncoder shaPasswordEncoder;

    @Autowired
    UserDetailsService userDetailService;

    @Autowired
    DaoAuthenticationProvider daoAuthenticationProvider; 

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(daoAuthenticationProvider);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(daoAuthenticationProvider);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authenticationProvider(daoAuthenticationProvider)
            .authorizeRequests()
            .antMatchers("/admin/**").hasRole("ADMIN")
            .antMatchers("/**").permitAll()
            .and().formLogin()
            .loginProcessingUrl("/login")
            .defaultSuccessUrl("/")
        .failureUrl("/login")
        .and()
        .logout();
    }

}

AuthorizationServerConfigurerAdapter is ..

@Configuration
@EnableAuthorizationServer
@EnableJpaRepositories(basePackages= {"kr.avansoft.bean.repository"})
public class AuthConfig extends AuthorizationServerConfigurerAdapter{

    @Autowired
    SHAPasswordEncoder passwordEncoder;


    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        security.passwordEncoder(passwordEncoder);
    }
}

Ответы [ 2 ]

0 голосов
/ 04 октября 2018

Также убедитесь, что версия spring-security-core является той же версией, что и версия spring-core или web или spring-boot (перекрестная проверка с репозиторием Maven).По крайней мере, в моем случае именно так я решил проблему.Произошло несоответствие версий зависимостей, что привело к конфликту зависимостей.

0 голосов
/ 11 июня 2018

Вам не нужно назначать кодировщик пароля для DaoAuthenticationProvider.На самом деле вам вообще не нужен DaoAuthenticationProvider.

Вы можете установить userDetailsService и passwordEncoder в bean-компоненте SecurityConfig:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
          .userDetailsService(userDetailsService)
          .passwordEncoder(passwordEncoder());
    } 

    private PasswordEncoder passwordEncoder() {
        PasswordEncoder encoder = new BCryptPasswordEncoder(); // or any other compatible encoder 
        return encoder;
    }
}

Еще одна важная деталь;если это не требуется специально из-за ваших обстоятельств, вы не должны использовать SHA для кодирования пароля.Обсуждается в длине здесь и здесь

...