java - SpringBoot 2.0.2.RELEASE 中的 BCryptPasswordEncoder 定义

标签 java spring spring-boot spring-security encoder

我有一个基本的 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);
    }

最佳答案

尝试在 com.bonanza.backend.service.UserService 中 Autowiring PassswordEncoder 可能可以解决问题。

 @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());

尝试一下..这肯定有效。

关于java - SpringBoot 2.0.2.RELEASE 中的 BCryptPasswordEncoder 定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50524577/

相关文章:

java - Spring webflux 中处理条件响应的正确方法是什么

java - 在 spring boot actuator 健康检查 API 中启用日志记录

java.lang.NoSuchMethodError : io. searchbox.action.Action.getURI()Ljava/lang/String

java - SimpleStringProperty set() 与 setValue()

java - 防止全屏应用程序中的屏幕截图(打印屏幕)

java - Android webview.postUrl(url,Encodingutils.getBytes(postData ,"BASE64")) 从 postdata 字符串中删除 "+"

java - @InitBinder 的 value 元素的用途是什么?

java - Android:微调器显示标题栏 1/2 秒

Spring Boot Data JPA - 不将实体保存到数据库

java - 如何在一次测试中启动2个Spring Boot应用程序?