1. 创建一个Spring Boot项目,添加Web和Security依赖。
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId>
</dependency>
2. 创建一个User实体类,用于存储用户信息。
public class User {private String username;private String password;// getter和setter方法
}
3. 创建一个UserDetailsService接口的实现类,用于加载用户信息。
@Service
public class UserDetailsServiceImpl implements UserDetailsService {@Overridepublic UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {// 从数据库或其他数据源获取用户信息User user = userRepository.findByUsername(username);if (user == null) {throw new UsernameNotFoundException("用户不存在");}return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), new ArrayList<>());}
}
4. 创建一个WebSecurityConfig类,继承WebSecurityConfigurerAdapter,并重写configure方法,配置SpringSecurity。
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {@Autowiredprivate UserDetailsService userDetailsService;@Overrideprotected void configure(HttpSecurity http) throws Exception {http.csrf().disable().authorizeRequests().antMatchers("/login").permitAll().anyRequest().authenticated().and().formLogin().loginPage("/login").permitAll().and().logout().permitAll();}@Autowiredpublic void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());}
}
5. 在Vue项目中创建一个登录组件,包含用户名和密码输入框以及登录按钮。使用axios发送POST请求到SpringBoot后端的/login接口。
<template><div><input v-model="username" placeholder="用户名" /><input v-model="password" type="password" placeholder="密码" /><button @click="login">登录</button></div>
</template><script>
import axios from "axios";export default {data() {return {username: "",password: "",};},methods: {async login() {try {const response = await axios.post("/login", {username: this.username,password: this.password,});if (response.data.success) {this.$router.push("/home");} else {alert("登录失败");}} catch (error) {console.error(error);}},},
};
</script>
6. 在Spring Boot后端的Controller中处理登录请求,验证用户名和密码是否正确,返回相应的响应。
@RestController
public class LoginController {@Autowiredprivate UserRepository userRepository;@PostMapping("/login")public ResponseEntity<?> login(@RequestBody User user) {User dbUser = userRepository.findByUsername(user.getUsername());if (dbUser != null && bcrypt.checkpw(user.getPassword().toCharArray(), dbUser.getPassword().toCharArray())) {return ResponseEntity.ok("登录成功");} else {return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("用户名或密码错误");}}
}
7. 运行Spring Boot项目和Vue项目,测试登录功能。