SpringBoot+vue使用bcrypt对注册密码加密及登录校验

一、注册

1.后端

在pom.xml文件中加入

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-crypto</artifactId>
</dependency>

lombok依赖

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
  </dependency>

创建一个用户实体类(User)来存储用户信息.

package com.test.pojo;

//使用lombok需要导入依赖
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private Integer id;
    private String username;
    private String password;
}

 创建一个用于注册的接口(RegisterController),在该接口中,将接收到的密码进行bcrypt加密后保存到数据库中。

package com.test.controller;


import com.test.pojo.User;
import com.test.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RegisterController {
    @Autowired
    private UserService userService;
    @PostMapping("/register")
    public String register(@RequestBody User user) {
        // 创建bcrypt密码编码器
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

        // 对密码进行bcrypt加密
        String encryptedPassword = passwordEncoder.encode(user.getPassword());

        // 更新用户对象的密码为加密后的密码
        user.setPassword(encryptedPassword);

        // 保存用户到数据库
        userService.save(user);

        return "注册成功";
    }

}

前端

<template>
    <div>
        <input type="text" v-model="username" placeholder="Username">
        <input type="password" v-model="password" placeholder="Password">
        <button @click="register">Register</button>
    </div>
</template>

<script>
import axios from 'axios';

export default {
    data() {
        return {
            username: '',
            password: ''
        };
    },
    methods: {
        register() {
            // 发送注册请求到后端
            axios.post('http://localhost:8080/register', {
                username: this.username,
                password: this.password
            })
            .then(response => {
                console.log(response.data);
                // 注册成功的处理逻辑
            })
            .catch(error => {
                console.error(error);
                // 注册失败的处理逻辑
            });
        }
    }
};
</script>

运行结果

 

二.登录

后端

package com.test.controller;

import com.test.pojo.User;
import com.test.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LoginController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public String login(@RequestBody User user) {
        // 根据用户名从数据库中获取用户信息
        User storedUser = userService.findByUserName(user.getUsername());

        if (storedUser == null) {
            return "User not found";
        }

        // 创建bcrypt密码编码器
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

        // 对用户输入的密码与数据库中的密码进行比对
        if (passwordEncoder.matches(user.getPassword(), storedUser.getPassword())) {
            return "Login successful";
        } else {
            return "Invalid credentials";
        }
    }
}

前端

<template>
    <div>
      <input type="text" v-model="username" placeholder="Username">
      <input type="password" v-model="password" placeholder="Password">
      <button @click="login">Login</button>
    </div>
  </template>
  
  <script>
  import axios from 'axios';
  
  export default {
    data() {
      return {
        username: '',
        password: ''
      };
    },
    methods: {
      login() {
        // 发送登录请求到后端
        axios.post('http://localhost:8080/login', {
          username: this.username,
          password: this.password
        })
        .then(response => {
          console.log(response.data);
          // 登录成功的处理逻辑
        })
        .catch(error => {
          console.error(error);
          // 登录失败的处理逻辑
        });
      }
    }
  };
  </script>
  

运行结果

注:若SpringBoot和Vue前后端无法实现交互,请看:SpringBoot与Vue前后端交互问题

完整代码:后端https://gitee.com/forget1204/2023-5-27bcryptjiami

posted @ 2023-05-27 22:37  万事胜意k  阅读(1592)  评论(0编辑  收藏  举报