首页 > 解决方案 > 我的 Spring Security 项目中的 BCrypt (Spring security)

问题描述

我该怎么做加密。这样在数据库中它就不会显示用户密码。我现在保存在数据库中 - 登录名和密码,用户角色。我需要密码必须在数据库中加密(BCrypt)

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/admin/**").hasRole("ADMIN")
                .antMatchers("/user/**").hasRole("USER")
                .antMatchers("/**").permitAll()
                .and()
                .formLogin()
                .loginPage("/login")
                .defaultSuccessUrl("/allStudents")
                .and()
                .logout()
                .and()
                .csrf().disable();
    }

    @Bean
    public PasswordEncoder weDoNotWantEncryption() {
        return new PasswordEncoder() {
            @Override
            public String encode(CharSequence rawPassword) {
                return rawPassword.toString();
            }

            @Override
            public boolean matches(CharSequence rawPassword, String encodedPassword) {
                return rawPassword.toString().equals(encodedPassword);
            }
        };
    }

}

标签: javaspringjakarta-eespring-security

解决方案


非常简单 - 只需将您的weDoNotWantEncryption()函数替换为返回 BCrypt 实例的函数:

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

BCryptPasswordEncoder实现PasswordEncoder(顾名思义),因此已经为encode()和定义了很好的方法matches()

请注意,这(当然)会使数据库中当前的任何密码都无法使用,尽管鉴于这些密码以明文形式存储,我假设(并希望/祈祷)这是在测试环境中,而不是在生产环境中。


推荐阅读