首页 > 解决方案 > Spring Boot 如何使用 BCrypt 进行身份验证/登录

问题描述

我目前正在使用 Spring Boot 和 Angular 创建一个应用程序,为此我需要一个用户。我已经创建了可以将散列的密码保存在数据库中。这很好用。但我不知道,如果我目前的解决方案有什么好处。我也不知道如何登录用户。有谁知道我能做什么或做什么?

UserController 在这里我发送我的 HTTP 请求。在这里,我加密密码并发送 HTTP 响应。

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

    @Autowired
    private PasswordEncoder passwordEncoder;

    @PostMapping
    public ResponseEntity<String> registerNewUserAccount(@Validated @RequestBody User accountDto) {
        accountDto.setPassword(passwordEncoder.encode(accountDto.getPassword()));
        if (userService.save(accountDto) == null) {
            return new ResponseEntity<>("E-Mail already exists", HttpStatus.CONFLICT);
        }
        return new ResponseEntity<>(null, HttpStatus.OK);
    }

UserServiceImpl 我在这里检查电子邮件是否已经存在。findByEmail 方法在 UserRepository 中。

    private final UserRepository userRepository;

    public UserServiceImpl(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public User save(User object) {
        if (userRepository.findByEmail(object.getEmail()) == null) {
            return userRepository.save(object);
        }
        return null;
    }

UserService(接口) 这是基本的。

public interface UserService extends CrudService<User, Integer> {
    User save(User object);
    List<User> findAll();
    void deleteById(Integer id);
    User findById(Integer id);
    void delete(User object);
}

标签: angularspring-boot

解决方案


https://github.com/arbiss1/SpringBootJpa-and-Security/tree/main/src/main/java/net/codejava

这是我的春季安全实施回购。循序渐进,你会得到你想要的。你的问题需要很多解释。


推荐阅读