I'm a beginner, I want to code the password when adding users but there is an error (@Bean
).
Error:
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
Description:
Field passwordEncoder in com.example.demo.service.UsersService required a bean of type 'org.springframework.security.crypto.password.PasswordEncoder' that could not be found.
The injection point has the following annotations:
- @org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'org.springframework.security.crypto.password.PasswordEncoder' in your configuration.
My code:
@Configuration
@EnableConfigurationProperties
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true, jsr250Enabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
UsersService userService;
@Override
protected void configure(HttpSecurity http) throws Exception {
// TODO Auto-generated method stub
http.csrf().disable() //TODO implement csrf
.cors().and().authorizeRequests().antMatchers(HttpMethod.OPTIONS,"/").permitAll()
.antMatchers("/login").permitAll()
.antMatchers("/add-users").permitAll()
.and().authorizeRequests().anyRequest().authenticated();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// TODO Auto-generated method stub
auth.userDetailsService(userService)
.passwordEncoder(passwordEncoder());
}
@Bean
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
// TODO Auto-generated method stub
return super.authenticationManagerBean();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
public class UsersService implements UserDetailsService {
@Autowired
UsersRepository repo;
@Autowired
private PasswordEncoder passwordEncoder;
public Users save(Users u) {
String encodpass=passwordEncoder.encode(u.getPassword());
String confpass=passwordEncoder.encode(u.getConfirmepass());
u.setConfirmpass(confpass);
u.setPassword(encodpass);
u.setLock(false);
u.setEnable(true);
return repo.save(u);
}
}
@RestController
public class UsersController {
@Autowired
private UsersService service;
@PostMapping("/add-users")
public Users add(@RequestBody Users u) {
return service.save(u);}
CodePudding user response:
add @Service annotation to UserService class. also add @EnableWebSecurity to config class.
CodePudding user response:
this is an alternative but i prefer adding password encoder bean declaration in a different beans.java file