Как я могу использовать Bcrypt в моем весеннем загрузочном приложении для защиты паролей? - PullRequest
0 голосов
/ 05 января 2020

Мои имя пользователя и пароль поступают с angular для весенней загрузки, которая хранит их в mysql. У меня есть простая модель, репозиторий, сервисы и пакеты контроллеров. Моя модель - это регистрация, в которой есть имя пользователя и пароль, и при входе в систему имя пользователя и пароль выбираются из таблицы регистрации

Мой класс модели регистрации


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 + "]";
    }



}

Мой контроллер регистрации


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;


    }

}

мне нужно добавить какой-либо файл конфигурации в пакет или мне нужно использовать bcrypt в angular? Youtube видео сбивают с толку, пожалуйста, помогите

1 Ответ

1 голос
/ 06 января 2020

Я думаю, что вы хотите Spring Security. В этом случае вы должны использовать BCryptPasswordEncoder . Просто создайте Bean для шифрования.

    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();
    }

Если вы просто хотите зашифровать пароль в BCrypt. Вы можете использовать как это

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