I have Spring boot app that uses mongo as db. I am using spring-security to secure my endpoints:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
However I would like to introduce login endpoint where users will be able to provide username & password. Once I have their credentials I am going to verify if such user (with this password and username) exists in mongodb. All of my attempts to retrieve the user by username and password from Mongodb failed.
My repository looks like:
public interface UserRepository extends MongoRepository<User, String> {
@Query("{ 'username' : ?0 }")
User findUserByUsername(String username);
@Query("{username : ?0, password : ?1}")
User findUserByUsernameAndPassword(String username, String password);
}
method User findUserByUsernameAndPassword(String username, String password); always returns null even though such user exists in db.
Application starts with the following configuration:
@SpringBootApplication
public class AccountApplication {
@Bean
RestTemplate restTemplate() {
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(AccountApplication.class, args);
}
}
@EnableWebSecurity
@Configuration
class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.addFilterAfter(new JWTAuthorizationFilter(), UsernamePasswordAuthenticationFilter.class)
.authorizeRequests()
.antMatchers(HttpMethod.POST, "/id/login", "/users").permitAll()
.antMatchers(HttpMethod.GET, "/users").permitAll()
.anyRequest().authenticated();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
Even if I tried to comment this row: .addFilterAfter(new JWTAuthorizationFilter(), UsernamePasswordAuthenticationFilter.class) the user can not be fetched by username and password.
How I can fetch the user by username and password?
Thanks in advance!
EDIT I founded the solution here: why spring security gives empty password to password encoder?
I forgot to set Getter of password field.