Java Spring Security - User.withDefaultPasswordEncoder() is deprecated?

前端 未结 2 1015
梦谈多话
梦谈多话 2020-12-28 16:23

I am very new to java spring security, and was following the Spring.io tutorial guide. As part of this, I edited the WebSecurityConfig class as required:

<
2条回答
  •  抹茶落季
    2020-12-28 17:07

    EDIT: deleted old answer, misunderstood the question. Here's the new one:

    User.withDefaultPasswordEncoder() can still be used for demos, you don't have to worry if that's what you're doing - even if it's deprecated - but in production, you shouldn't have a plain text password in your source code.

    What you should be doing instead of using your current userDetailsService() method is the following:

    private static final String ENCODED_PASSWORD = "$2a$10$AIUufK8g6EFhBcumRRV2L.AQNz3Bjp7oDQVFiO5JJMBFZQ6x2/R/2";
    
    
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
            .passwordEncoder(passwordEncoder())
            .withUser("user").password(ENCODED_PASSWORD).roles("USER");
    }
    
    
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
    

    Where ENCODED_PASSWORD is secret123 encoded with BCrypt. You can also encode it programmatically like so: passwordEncoder().encode("secret123").

    That way, even if you push your code to a public repository, people won't know the password because ENCODED_PASSWORD only shows the encoded version of the password and not the plain text version, but because you know that $2a$10$AIUufK8g6EFhBcumRRV2L.AQNz3Bjp7oDQVFiO5JJMBFZQ6x2/R/2 is actually the encoded password of the string secret123 whereas others don't, your in-memory user with the credentials user:secret123 won't be compromised.

    Note that I'm using leaving it in a static variable for the sake of the example.

提交回复
热议问题