spring - 考虑在您的配置中定义一个类型为 'org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder' 的 bean

标签 spring spring-boot spring-security

我正在尝试将 jwt token 连接到我的项目,但在工作期间我遇到了一些问题。我遵循了提到的说明 here ,但我有错误。我试图用来自 these guys 的相同问题修复它,但它对我不起作用。我想,我错过了一些东西。

谁能帮帮我,谢谢。

错误:

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

Description:

Parameter 1 of constructor in com.example.demo.security.WebSecurity 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.


WebSecurity.java
@EnableWebSecurity
public class WebSecurity extends WebSecurityConfigurerAdapter {
    private AppUserDetailsService appUserDetailsService;
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    public WebSecurity(AppUserDetailsService appUserDetailsService, BCryptPasswordEncoder bCryptPasswordEncoder) {
        this.appUserDetailsService = appUserDetailsService;
        this.bCryptPasswordEncoder = bCryptPasswordEncoder;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable().authorizeRequests()
                .antMatchers(HttpMethod.POST).permitAll()
                .anyRequest().authenticated()
                .and()
                .addFilter(new JWTAuthenticationFilter(authenticationManager()))
                .addFilter(new JWTAuthorizationFilter(authenticationManager()))
                // this disables session creation on Spring Security
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.csrf().disable();
    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(appUserDetailsService).passwordEncoder(bCryptPasswordEncoder);
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
        return source;
    }
}

AppUserDetailsS​​ervice.java
@Service
public class AppUserDetailsService implements UserDetailsService {
    private UserRepository userRepository;

    public AppUserDetailsService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Users user = userRepository.findByUsername(username);

        if (user == null)
            throw new UsernameNotFoundException(username);

        return new User(user.getUsername(), user.getPassword(), emptyList());
    }
}

JWTAuthenticationFilter.java
public class JWTAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
    @Autowired
    private AuthenticationManager authenticationManager;

    public JWTAuthenticationFilter (AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    @Override
    public Authentication attemptAuthentication (HttpServletRequest req, HttpServletResponse res) {
        try {
            Users creds = new ObjectMapper().readValue(req.getInputStream(), Users.class);

            return authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(
                            creds.getUsername(),
                            creds.getPassword(),
                            new ArrayList<>())
            );
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    protected void successfulAuthentication(HttpServletRequest req,
                                            HttpServletResponse res,
                                            FilterChain chain,
                                            Authentication auth) throws IOException, ServletException {

        String token = JWT.create()
                .withSubject(((User) auth.getPrincipal()).getUsername())
                .withExpiresAt(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .sign(HMAC512(SECRET.getBytes()));
        res.addHeader(HEADER_STRING, TOKEN_PREFIX + token);
    }
}

最佳答案

将此@Bean 添加到您的 WebSecurity 配置中:

@Bean
public BCryptPasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}

此外,从构造函数中删除 BCryptPasswordEncoder,包括该字段。

关于spring - 考虑在您的配置中定义一个类型为 'org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder' 的 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60848619/

相关文章:

java - 在 Spring 中删除和重新创建数据库模式的新方法?

java - 将 spring oauth db 从内存迁移到 jdbc

java - 如何获取java应用程序的所有包?

spring-mvc - Spring Boot 白标错误页面

java - 设置 Spring Security : Invalid content was found starting with element 'security:http'

java - 在AWS上发布Springboot webapp 404索引错误

maven - 在加特林模拟之前启动 spring-boot 应用程序

java - 为 Spring Security 设置 LDAP 查询超时

spring - spring-security.xml 错误 "Configuration problem: spring-security-web classes are not available. You need these to use <filter- chain-map>"

java - Spring Boot : Interceptor to read particular field from request and set it in the response