Search code examples
springspring-bootbcrypt

How do I use Bcrypt in my spring boot application to secure passwords?


My username and password is coming from angular to spring boot which stores it in mysql. I have simple model, repository, services and controller packages. My model is registration which has name username and password and while loggin in, the username and password is fetched from the registration table

My Registration Model Class


package com.example.angular.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;


@Entity
@Table(name="registration")
public class Registration {

    @Id
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    private int id;

    private String name;
    private String username;
    private String password;
    public int getId() {
        return id;
    }
    public String getName() {
        return name;
    }
    public String getUsername() {
        return username;
    }
    public String getPassword() {
        return password;
    }
    public void setId(int id) {
        this.id = id;
    }
    public void setName(String name) {
        this.name = name;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public Registration(String name, String username, String password) {
        super();
        this.name = name;
        this.username = username;
        this.password = password;
    }
    public Registration() {
        super();
        // TODO Auto-generated constructor stub
    }
    @Override
    public String toString() {
        return "Registration [id=" + id + ", name=" + name + ", username=" + username + ", password=" + password + "]";
    }



}

My registration controller


import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.angular.model.Registration;
import com.example.angular.service.RegistrationService;

@RestController
@CrossOrigin(origins="*", allowedHeaders = "*")
@RequestMapping("/register")
public class RegistrationController {

    @Autowired
    private RegistrationService res;

    @PostMapping("/registeruser")
    public ResponseEntity<Registration> registeruser(@RequestBody  Registration reg)
    {


        Registration resk= res.registeruser(reg);

        return new ResponseEntity<Registration>(resk,HttpStatus.OK);


    }


    @PostMapping("/login")
    public ResponseEntity<Registration> loginuser(@RequestBody  Registration reg)
    {


        List<Registration> regList = res.getusername(reg.getUsername(), reg.getPassword());



            System.out.println("Logged in! ");
        //return new ResponseEntity<Registration>(reg.getUsername(), HttpStatus.OK);

    return null;


    }

}

do I have to add any configuartion file in a package or do I have to use bcrypt in angular? Youtube videos are confusing please help


Solution

  • I think you want Spring Security. In this case you should use BCryptPasswordEncoder. Simply create Bean for encryption.

        private static final String ADMIN = "ADMIN";
        private static final String USER = "USER";
    
        @Autowired
        private UserDetailService userDetailService;
    
        @Autowired
        private DataSource dataSource;
    
        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(userDetailsService).dataSource(dataSource)
                    .passwordEncoder(passwordEncoder());
        }
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.csrf().disable().authorizeRequests()
                    .antMatchers("/admin").hasRole(ADMIN)
                    .antMatchers("/user").hasAnyRole(ADMIN, USER)
                    .antMatchers("/", "/register-user").permitAll()
                    .and().formLogin();
        }
    
        @Bean
        public BCryptPasswordEncoder passwordEncoder() {
            return new BCryptPasswordEncoder();
        }
    
    

    If you just want to encrypt the password in BCrypt. You can use like this

    String password = "password";
    BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    String hashedPassword = passwordEncoder.encode(password);