弹簧安全配置中的bcryptencoder配置

发布于 2025-02-13 10:36:23 字数 2280 浏览 0 评论 0原文

因此,我正在创建此休息服务,但我正在为EscoderConfiguration苦苦挣扎。

如下所示,我创建了一个配置类来设置passwordencoderbean。

我的代码编译。但是,当我尝试登录时,我会得到“不良凭据”,是的,我相信我正在使用正确的凭据。也的是,我的数据库中的密码在其前面用{bcrypt}对其进行了bcryptencod。我的猜测是我错误地配置了此密码编码器配置。配置中的故障在哪里?

在我的passwordencodeconfig下方:

@Configuration
public class PasswordEncoderConfig {
    @Bean
    public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }
}

当前的springsecurityconfiguration:


@EnableWebSecurity
class SecurityConfiguration extends WebSecurityConfigurerAdapter{
    private static final String ADMIN = "ROLE_ADMIN";
    private static final String WORKER = "ROLE_WORKER";
    
    private final DataSource dataSource;
    private PasswordEncoder bcryptencoder;
    
    public SecurityConfiguration(DataSource dataSource,  PasswordEncoder bcryptencoder) {
        this.dataSource = dataSource;
        this.bcryptencoder = bcryptencoder;
    }
    
    /*@Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }*/
    
    
    
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication().dataSource(dataSource)
            .usersByUsernameQuery("select voornaam as username, password as password, true as enabled from gebruikers where voornaam = ?")
            .passwordEncoder(bcryptencoder)
            .authoritiesByUsernameQuery("select voornaam as username, role as authorities from gebruikers where voornaam = ?");
        
            
    }
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring()
        .mvcMatchers("/images/**")
        .mvcMatchers("/css/**")
        .mvcMatchers("/js/**");
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable();
        /*remove after postman, @cross origin*/
        http.formLogin();
        http.authorizeHttpRequests(requests -> requests
            .mvcMatchers("/**").hasAnyAuthority(ADMIN, WORKER)
            .mvcMatchers("/gebruikers/**").hasAnyAuthority(ADMIN, WORKER));
        http.logout();
        
    }
    


}

So I'm creating this restservice but I am struggling with the encoderconfiguration.

I created a config class to set the passwordencoderBean, as instructed in replies below.

My code compiles. But when I try to log in, I get 'Bad Credentials', and yes I am sure I am using right credentials. Also Yes, the password in my database is Bcryptencoded with {bcrypt} in front of it. My guess is that I am misconfiguring this passwordEncoder configuration.Where lies the fault in configuration?

Here below my passwordencodeConfig:

@Configuration
public class PasswordEncoderConfig {
    @Bean
    public PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }
}

current SpringSecurityConfiguration:


@EnableWebSecurity
class SecurityConfiguration extends WebSecurityConfigurerAdapter{
    private static final String ADMIN = "ROLE_ADMIN";
    private static final String WORKER = "ROLE_WORKER";
    
    private final DataSource dataSource;
    private PasswordEncoder bcryptencoder;
    
    public SecurityConfiguration(DataSource dataSource,  PasswordEncoder bcryptencoder) {
        this.dataSource = dataSource;
        this.bcryptencoder = bcryptencoder;
    }
    
    /*@Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }*/
    
    
    
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication().dataSource(dataSource)
            .usersByUsernameQuery("select voornaam as username, password as password, true as enabled from gebruikers where voornaam = ?")
            .passwordEncoder(bcryptencoder)
            .authoritiesByUsernameQuery("select voornaam as username, role as authorities from gebruikers where voornaam = ?");
        
            
    }
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring()
        .mvcMatchers("/images/**")
        .mvcMatchers("/css/**")
        .mvcMatchers("/js/**");
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable();
        /*remove after postman, @cross origin*/
        http.formLogin();
        http.authorizeHttpRequests(requests -> requests
            .mvcMatchers("/**").hasAnyAuthority(ADMIN, WORKER)
            .mvcMatchers("/gebruikers/**").hasAnyAuthority(ADMIN, WORKER));
        http.logout();
        
    }
    


}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

星光不落少年眉 2025-02-20 10:36:23

要走的方法是使用

@Bean
public PasswordEncoder passwordEncoder()
{
    return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}

它使用bcrypt作为默认值,但为将来的迁移提供了更好的接口。请注意,生成的密码具有前缀:

With Factory:
{bcrypt}$2a$10$Zz3xIJON0d1GI0vqMULIKOHCImVnFCWMNRE3Vw0ElvSmfCqGcDV5W

Without:
$2a$10$Zz3xIJON0d1GI0vqMULIKOHCImVnFCWMNRE3Vw0ElvSmfCqGcDV5W

当您使用工厂并提供没有前缀的BCrypt哈希时,它将被拒绝为无效。

编辑:正如Chaosfire所说的那样,您定义了一个圆形的豆定义。 Spring不用将其注入字段,而可以使用该方法进行BEAN声明,而是将实例注入方法调用,因此您最终将使用相同的密码编码器,您在Bean声明中提供了相同的密码编码器。

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.jdbcAuthentication().dataSource(dataSource)
        .usersByUsernameQuery("select voornaam as username, password as password, true as enabled from gebruikers where voornaam = ?")
        .passwordEncoder(passwordEncoder()) // referencing bean, not field
        .authoritiesByUsernameQuery("select voornaam as username, role as authorities from gebruikers where voornaam = ?");

The way to go is to use

@Bean
public PasswordEncoder passwordEncoder()
{
    return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}

It uses BCrypt as the default but provides a better interface for future migration. Note that the generated password has a prefix:

With Factory:
{bcrypt}$2a$10$Zz3xIJON0d1GI0vqMULIKOHCImVnFCWMNRE3Vw0ElvSmfCqGcDV5W

Without:
$2a$10$Zz3xIJON0d1GI0vqMULIKOHCImVnFCWMNRE3Vw0ElvSmfCqGcDV5W

When you use the factory and provided a bcrypt hash without the prefix, it will be rejected as invalid.

Edit: And as Chaosfire said it, you defined a circular bean definition. Instead of injecting it to a field, you can use the method for the bean declaration, spring will inject the instance to the method call, so you end up with the same password encoder, which you provided at the bean declaration.

@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    auth.jdbcAuthentication().dataSource(dataSource)
        .usersByUsernameQuery("select voornaam as username, password as password, true as enabled from gebruikers where voornaam = ?")
        .passwordEncoder(passwordEncoder()) // referencing bean, not field
        .authoritiesByUsernameQuery("select voornaam as username, role as authorities from gebruikers where voornaam = ?");
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文