bugfix> java > 投稿

基本的な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);
    }

回答 1 件
  • で自動配線PassswordEncoderをお試しください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;
        }
    
    

    そして、 auth.passwordencode(passwordencodebean()) を置き換えます   auth.authenticationProvider(authenticationProvider()); へ にconfigureGlobal() 方法

    試してみてください。

あなたの答え