SpringBoot 2.0.2.RELEASE 中的 BCryptPasswordEncoder 定义

2024-01-18

我有一个基本的 Spring Boot 应用程序。使用 Spring Initializr、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);
    }

尝试在您的中自动装配 PassswordEncodercom.bonanza.backend.service.UserService可能可以解决问题。

 @Autowired
    private PasswordEncoder bCryptPasswordEncoder;

Edited

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

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

然后替换auth.passwordencode(passwordencodebean()) to auth.authenticationProvider(authenticationProvider());in 配置全局() method

尝试一下..这肯定会起作用。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

SpringBoot 2.0.2.RELEASE 中的 BCryptPasswordEncoder 定义 的相关文章

随机推荐

  • 监控 Netty 事件循环队列的大小

    我们已经实现了对 Netty 事件循环队列的监控 以便了解一些 Netty 模块的问题 该显示器使用io netty util concurrent SingleThreadEventExecutor pendingTasks方法 适用于大
  • XSLT - 应用模板中包含多个节点的通用规则

    我正在根据父亲的字段对祖父母进行排序 源文件看起来像
  • 构造函数不运行

    我不明白 因为当您创建 Users 类的对象时 不会打印包含构造函数的消息 class users public users private int i users users cout lt lt hello world int main
  • 如何判断一个节点是在内存中还是在 dom 中?

    在将节点附加到主页的 DOM 之前 我对节点进行了大量工作 我需要根据给定节点是否包含在主文档中来执行一些工作 我目前的方法是通过以下方式联系父母 if this el closest body length gt 0 有没有更合适的方法来
  • 类型错误:firebase.auth(...).onAuthStateChanged 不是函数

    我正在尝试使用 onAuthStateChanged 触发器 但在使用 firebase 部署 时收到 不是函数 执行时 firebase deploy 我收到以下错误 Error Error occurred while parsing
  • 如何使用 PHP/IIS 读取 Windows 登录用户名

    我正在运行一个网络 这里我有一个域控制器 DC 我刚刚在上面安装了 IIS6 PHP 和 Mysql 一切都很好 现在我想在这个本地网站上启动一个脚本 第一个问题是我想检测哪个网络用户 活动目录用户 使用PHP登录 我的意思是 当用户登录到
  • Git Flow 流程发送用于测试的功能,仅将特定功能部署到上线

    我们正在努力解决 Git Flow 流程 并将功能部署到我们的测试和实时环境 我们希望所有已准备好测试的功能都可以combined并部署到测试环境 我们只想部署具体特征到现场环境 我们使用 Git Flow 的方式存在的问题 开发人员 A
  • 如何在 JavaScript 中运行对象的 onEvent 方法?

    我刚刚开始使用 javascript 但我遗漏了一些我所知道的重要内容 我希望你能帮助我填补这个空白 因此 我尝试运行的脚本应该计算文本字段中的字符数 并更新一个段落以告诉用户他们输入了多少个字符 我有一个名为 charCounter 的对
  • R Plotly 叠加条形图

    简而言之问题 使用R和Plotly包 我可以创建一个覆盖条形图 其中使用 x 轴上的相同位置显示 2 个系列吗 经过相当多的谷歌搜索后 我找不到答案 例如这个可视化 使用 Plotly 和 R 创建分组 非重叠 堆叠条形图的代码 month
  • Horizo​​ntal Pod Autoscaler 中 API 版本 v2beta1 和 v2beta2 之间的区别?

    Kubernetes Horizo ntal Pod Autoscaler 演练https kubernetes io docs tasks run application horizo ntal pod autoscale walkthr
  • LINQ to SQL - 在保存之前格式化字符串?

    我正在尝试将现有 非 LINQ to SQL 类转换为 LINQ to SQL 实体类 该实体类具有现有 db 列 属性 例如 public string MyString get return myString set myString
  • 如何选择每个卷积层的滤波器数量? [关闭]

    Closed 这个问题需要多问focused help closed questions 目前不接受答案 构建卷积神经网络时 如何确定每个卷积层使用的滤波器数量 我知道关于过滤器的数量没有硬性规定 但是根据您的经验 您读过的论文等 是否对所
  • 为什么 EAX 中的高 16 位不能通过名称访问(如 AX、AH 和 AL)? [复制]

    这个问题在这里已经有答案了 为什么没有一个特定的寄存器来访问寄存器的其他部分 16 32 Like ah or al访问8位部分ax登记 我们的想法是将寄存器扩展到 32 位 而不是创建具有两倍数量的 16 或 8 位寄存器的机器 因为这些
  • 动态设置ContentProvider的权限

    也许标题有点误导 我的问题是我有一个 Android 库项目 该项目在两个标准 Android 项目之间共享 一个用于应用程序的免费版本 另一个用于付费版本 该库当前拥有 ContentProvider 的代码 包括一个合约类 其中包含多个
  • 有没有办法从对象中删除未知事件侦听器?

    我想要一个可重用的按钮 可以为由外部源确定的许多不同回调之一注册 当设置新的回调时 我想删除旧的 我还希望能够随时从外部清除回调 public function registerButtonCallback function Functio
  • luceneMatchVersion“LUCENE_36”无效

    我正在尝试将 Solr 3 6 2 集成到我的项目中 我使用 Maven 和 Tomcat 来运行这些东西 当我使用 HttpSolrServer 时一切都很好 但是当我更改为 EmbeddedSolrServer 时 它会出现这样的错误
  • file:/// 到 http:// 通过 IFrame 进行通信

    也许你们中的一些人可能遇到了我遇到的同样的问题 假设您的计算机上有一个文件 file c test html 该文件中有一个 IFrame 您需要指示 IFrame 内容是否已加载 基本上 我们这里有 1 无法从 file 访问位置 hre
  • A:边缘焦点解决方法

    我目前正在使用伪选择器 focus within in chrome 但是根据caniuse com https caniuse com feat css focus within它在 Edge 和 IE 中不可用 我找到了一个巧妙的解决方
  • 亚马逊 DynamoDB 和 AngularJS

    因此 我创建了一个 AWS dynamoDB 表 数据库 并准备使用 AngularJS 获取该数据 我如何使用 AngularJS 做到这一点 我需要在亚马逊设置其他服务吗 或者我可以直接访问我的数据库吗 我无法直接找到与 DynamoD
  • SpringBoot 2.0.2.RELEASE 中的 BCryptPasswordEncoder 定义

    我有一个基本的 Spring Boot 应用程序 使用 Spring Initializr JPA 嵌入式 Tomcat Thymeleaf 模板引擎 并打包为可执行 JAR 文件 我定义了这个配置文件 Configuration Enab