Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/384.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java SpringBoot 2.0.2.0版本中的BCryptPasswordEncoder定义_Java_Spring_Spring Boot_Spring Security_Encoder - Fatal编程技术网

Java SpringBoot 2.0.2.0版本中的BCryptPasswordEncoder定义

Java SpringBoot 2.0.2.0版本中的BCryptPasswordEncoder定义,java,spring,spring-boot,spring-security,encoder,Java,Spring,Spring Boot,Spring Security,Encoder,我有一个基本的SpringBoot应用程序。使用Spring初始值设定项、JPA、嵌入式Tomcat、Thymeleaf模板引擎,并将包作为可执行JAR文件。 我已经定义了这个配置文件 @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class ApiWebSecurityConfig extends WebSecurityConfigurerAdapter {

我有一个基本的SpringBoot应用程序。使用Spring初始值设定项、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);
    }
@Bean
公共密码编码器passwordEncoderBean(){
字符串idForEncode=“bcrypt”;
//这是我们用于编码的ID。
字符串currentId=“pbkdf2.2018”;
//我们支持的所有编码器的列表。旧的仍然需要在这里滚动更新
映射编码器=新的HashMap();
put(“bcrypt”,新的BCryptPasswordEncoder());
//编码器.put(currentId,新的Pbkdf2PasswordEncoder(PBKDF2_2018_SECRET,PBKDF2_2018_ITERATIONS,PBKDF2_2018_HASH_WIDTH));
编码器.put(currentId,新的Pbkdf2PasswordEncoder());
//返回新的DelegatingPasswordEncoder(idForEncode,编码器);
返回新的DelegatingPasswordEncoder(idForEncode,编码器);
}

在您的com.bonanza.backend.service.UserService中尝试自动连接Passwordencoder 可能是解决问题的办法

 @Autowired
    private PasswordEncoder bCryptPasswordEncoder;
已编辑

在配置文件中,首先添加

@Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
        authenticationProvider.setUserDetailsService(jwtuserDetailsService);
        authenticationProvider.setPasswordEncoder(passwordEncoderBean());
        return authenticationProvider;
    }
然后将
auth.passwordencode(passwordencodebean())
替换为
auth.authenticationProvider(authenticationProvider())配置全局()方法中


试试看..这肯定会奏效。

相同的结果:-(我已经在上面的答案中编辑了代码..你试过了吗?方法authenticationProvider(DaoAuthenticationProvider)对于类型DAOAuthenticationConfigurer是未定义的检查此示例..它对我来说很好。。