【问题标题】:BCryptPasswordEncoder definition in SpringBoot 2.0.2.RELEASESpringBoot 2.0.2.RELEASE 中的 BCryptPasswordEncoder 定义
【发布时间】:2018-11-04 13:55:51
【问题描述】:

我有一个基本的 SpringBoot 应用程序。使用 Spring Initializer、JPA、嵌入式 Tomcat、Thymeleaf 模板引擎,并将其打包为可执行 JAR 文件。 我已经定义了这个配置文件。

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class ApiWebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JwtAuthenticationEntryPoint unauthorizedHandler;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private JwtUserDetailsService jwtUserDetailsService;

    @Value("${jwt.header}")
    private String tokenHeader;

    @Value("${jwt.route.authentication.path}")
    private String authenticationPath;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .userDetailsService(jwtUserDetailsService)
            .passwordEncoder(passwordEncoderBean());
    }

    @Bean
    public PasswordEncoder passwordEncoderBean() {
        return new BCryptPasswordEncoder();
    }

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

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
            // we don't need CSRF because our token is invulnerable
            .csrf().disable()

            .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()

            // don't create session
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
            .authorizeRequests()

            // Un-secure H2 Database
            .antMatchers("/h2-console/**/**").permitAll()
            .antMatchers("/auth/**").permitAll()
            .anyRequest().authenticated();

        // Custom JWT based security filter
        JwtAuthorizationTokenFilter authenticationTokenFilter 
                            = new JwtAuthorizationTokenFilter(userDetailsService(), jwtTokenUtil, tokenHeader);

        httpSecurity
            .addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

        // disable page caching
        httpSecurity
            .headers()
            .frameOptions().sameOrigin()  // required to set for H2 else H2 Console will be blank.
            .cacheControl();
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        // AuthenticationTokenFilter will ignore the below paths
        web
            .ignoring()
            .antMatchers(
                HttpMethod.POST,
                authenticationPath
            )

            // allow anonymous resource requests
            .and()
            .ignoring()
            .antMatchers(
                HttpMethod.GET,
                "/",
                "/*.html",
                "/favicon.ico",
                "/**/*.html",
                "/**/*.css",
                "/**/*.js"
            )

            // Un-secure H2 Database (for testing purposes, H2 console shouldn't be unprotected in production)
            .and()
            .ignoring()
            .antMatchers("/h2-console/**/**");
    }
}

但是当我启动应用程序时。使用 Eclipse IDE 我在控制台中收到此错误:

***************************
APPLICATION FAILED TO START
***************************

Description:

Field passwordEncoder in com.bonanza.backend.service.UserService required a bean of type 'org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder' that could not be found.


Action:

Consider defining a bean of type 'org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder' in your configuration.

连 bean 都在配置文件中明确定义..

我也尝试使用具有相同结果的其他定义

@Bean
    public PasswordEncoder passwordEncoderBean() {

            String idForEncode = "bcrypt";
        // This is the ID we use for encoding.
        String currentId = "pbkdf2.2018";

        // List of all encoders we support. Old ones still need to be here for rolling updates
        Map<String, PasswordEncoder> encoders = new HashMap<>();
        encoders.put("bcrypt", new BCryptPasswordEncoder());
        //encoders.put(currentId, new Pbkdf2PasswordEncoder(PBKDF2_2018_SECRET, PBKDF2_2018_ITERATIONS, PBKDF2_2018_HASH_WIDTH));
        encoders.put(currentId, new Pbkdf2PasswordEncoder());

        //return new DelegatingPasswordEncoder(idForEncode, encoders);
        return new DelegatingPasswordEncoder(idForEncode, encoders);
    }

【问题讨论】:

    标签: java spring spring-boot spring-security encoder


    【解决方案1】:

    在您的 com.bonanza.backend.service.UserService 中尝试自动装配密码编码器 或许能解决问题。

     @Autowired
        private PasswordEncoder bCryptPasswordEncoder;
    

    已编辑

    在你的配置文件中首先添加

    @Bean
        public DaoAuthenticationProvider authenticationProvider() {
            DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
            authenticationProvider.setUserDetailsService(jwtuserDetailsService);
            authenticationProvider.setPasswordEncoder(passwordEncoderBean());
            return authenticationProvider;
        }
    

    然后在configureGlobal()方法中将auth.passwordencode(passwordencodebean())替换为auth.authenticationProvider(authenticationProvider());

    试试吧..这肯定会奏效的。

    【讨论】:

    • 同样的结果 :-(
    • 我已经在上面的答案中编辑了代码..你试过了吗?
    • 方法 authenticationProvider(DaoAuthenticationProvider) 未定义为 DaoAuthenticationConfigurer 类型
    • 检查这个例子..它对我来说很好..websystique.com/spring-security/…
    猜你喜欢
    • 2021-09-15
    • 2018-11-02
    • 2018-10-22
    • 2018-11-26
    • 2023-02-22
    • 2018-11-12
    • 2019-01-13
    • 1970-01-01
    • 2019-02-06
    相关资源
    最近更新 更多