4

My configuration:

   @Autowired
    private PasswordEncoder passwordEncoder;

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

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    // @Autowired
    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .userDetailsService(jwtUserDetailsService)
                .passwordEncoder(passwordEncoder);
    }

this code works fine. But if I remove @Autowired from passwordEncoder, then I must add @Autowired on the configure method. But this rules not apply on authenticationManagerBean() method. Can anyone explain ?

Ori Marko
  • 56,308
  • 23
  • 131
  • 233
chandrakant
  • 370
  • 3
  • 25
  • 2
    I think you should show more of the code to make this question better. Do you have a bean configuration .xml file or not? – A_C Dec 12 '18 at 14:09
  • 1
    "But this rules not apply on authenticationManagerBean() method" Of course, since you override it (cannot add PasswordEncoder as parameter) –  Dec 12 '18 at 14:12
  • I don't know exactly your goal with this approach, but you have two different passwordEncoder in your example. The interface declaration (where you need to include the @Autowired) and one method that returns one BCryptPasswordEncoder instance (unused). – Jonatas Emidio Dec 13 '18 at 11:31

3 Answers3

1

Look at this URL https://spring.io/guides/topicals/spring-security-architecture/ It seems that you Autowire AuthenticationManagerBuilder auth as a @Bean here.

Configure(AuthenticationManagerBuilder auth) so it will work in this case and passwordEncoder is also Autowired.

Menol
  • 1,230
  • 21
  • 35
Markovitz
  • 41
  • 3
  • you are right. Spring Boot provides a default global AuthenticationManager. So why i need Autowired with PasswordEncoder but not need AuthenticationManager. – chandrakant Dec 13 '18 at 05:02
1

It seems you use Spring annotations configuration,

If you don't add Spring annotations to method or field, Spring doesn't know it need to be initiated and therefore when used in Spring context ( also without initialize it outside Spring), objects will be null

Ori Marko
  • 56,308
  • 23
  • 131
  • 233
1

For security reasons you need to avoid storing the password in plaintext. based on this principle you have this option to encode your password.

In your example, you are using the PasswordEncoder interface:

.passwordEncoder(passwordEncoder);

Using this approach you must inform one implementation. In Spring you can inject this implementation using @Autowired (in the declaration or like your code on the method that use your PasswordEncoder interface).

Just a question... Why you created one implementation?

public PasswordEncoder passwordEncoderBean(){...

I think that this method can be replaced for your Autowired encode interface.