Bledar
Bledar

Reputation: 31

Spring Security Authentication

I can't do the authentication in spring using spring security using MongoDB.

Entity :

@Document(collection = "users")
public class Users {

    @Id
    private String id;
    private String username;
    private String email;
    private String password;
    private List<Notification> preferences;


    public Users(String username, String email, String password, List<Notification> preferences) {
        this.username = username;
        this.email = email;
        this.password = password;
        this.preferences = preferences;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public List<Notification> getPreferences() {
        return preferences;
    }

    public void setPreferences(List<Notification> preferences) {
        this.preferences = preferences;
    }
}

Service :

@Component
public class MongoUserDetailsService implements UserDetailsService {

    @Autowired
    private UserRepository repository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Users user = repository.findByUsername(username);

        if(user == null) {
            throw new UsernameNotFoundException("User not found");
        }

        List<SimpleGrantedAuthority> authorities = Arrays.asList(new SimpleGrantedAuthority("user"));

        return new User(user.getUsername(), user.getPassword(), authorities);
    }
}

Repository :

import com.example.Start.entities.Users;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;

@Repository
public interface UserRepository extends MongoRepository<Users, String> {
    Users findByUsername(String username);
}

Configuration :

    @Configuration
    @EnableConfigurationProperties
    public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

        @Autowired
        MongoUserDetailsService userDetailsService;

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                    .csrf().disable()
                    .authorizeRequests().anyRequest().authenticated()
                    .and().httpBasic()
                    .and().sessionManagement().disable();
        }

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

        @Override
        public void configure(AuthenticationManagerBuilder builder) throws Exception {
            builder.userDetailsService(userDetailsService);
        }
    }

When i try to authenticate it gives me this : enter image description here

In My database i have this user :

{
    "_id" : ObjectId("5b855813d03cce0264de3ab6"),
    "username" : "username",
    "email" : "[email protected]",
    "password" : "123"
}

Any idea what is causing this ?

Upvotes: 1

Views: 236

Answers (1)

shazin
shazin

Reputation: 21903

The problem is you have registered a BCryptPasswordEncoder as passwordEncoder bean but you have stored the password in clear text in database. Now when the Authentication is taking place it is encoding the incoming password from the HTTP request with BCrypt algorithm and compare it to the clear text password which will obviously fail. That is why you get "Encoded password does not look like BCrypt" because it is not.

The short fix will be to edit your mongodb user record to have the following value for password field of user with username "username" like following:

{
    "_id" : ObjectId("5b855813d03cce0264de3ab6"),
    "username" : "username",
    "email" : "[email protected]",
    "password" : "$2a$10$pIUUIHClmGYBnsJzlOHQkeecSwRGAgYlxzRfBFjEqhk6rkQdilTYC"
}

When you encode string "123" with BCrypt algorithm you will get "$2a$10$pIUUIHClmGYBnsJzlOHQkeecSwRGAgYlxzRfBFjEqhk6rkQdilTYC".

but the correct fix will be add code to encode your passwords before saving in Mongo database in the application like following:

@Autowired
private PasswordEncoder passwordEncoder;

public void saveUser(Users user) {
    user.setPassword(passwordEncoder.encoder(user.getPassword()));
    // Save in mongodb
}

Upvotes: 1

Related Questions