vue3+springboot2实现用户登录功能代码及数据库表
时间: 2023-07-30 16:10:14 浏览: 106
以下是基于Vue3和Spring Boot 2实现用户登录功能的代码和数据库表:
## 前端代码 (Vue3)
### Login.vue
```html
<template>
<div class="login-container">
<h2>用户登录</h2>
<form @submit.prevent="handleSubmit">
<label for="username">用户名:</label>
<input type="text" id="username" v-model="username" required>
<label for="password">密码:</label>
<input type="password" id="password" v-model="password" required>
<button type="submit">登录</button>
</form>
</div>
</template>
<script>
import { ref } from 'vue';
import axios from 'axios';
export default {
name: 'Login',
setup() {
const username = ref('');
const password = ref('');
const handleSubmit = async () => {
try {
const response = await axios.post('/api/login', { username: username.value, password: password.value });
localStorage.setItem('token', response.data.token);
// 登录成功跳转到首页
router.push('/');
} catch (error) {
console.log(error);
}
};
return {
username,
password,
handleSubmit,
};
},
};
</script>
```
## 后端代码 (Spring Boot 2)
### UserController.java
```java
@RestController
@RequestMapping("/api")
public class UserController {
@Autowired
private UserService userService;
@PostMapping("/login")
public ResponseEntity<?> login(@RequestBody LoginRequest loginRequest) {
Authentication authentication = authenticationManager.authenticate(
new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
String token = jwtProvider.generateToken(authentication);
return ResponseEntity.ok(new JwtAuthenticationResponse(token));
}
}
```
### UserService.java
```java
@Service
public class UserService implements UserDetailsService {
@Autowired
private UserRepository userRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepository.findByUsername(username)
.orElseThrow(() -> new UsernameNotFoundException("User not found with username: " + username));
return UserPrincipal.create(user);
}
}
```
### JwtProvider.java
```java
@Component
public class JwtProvider {
@Value("${app.jwtSecret}")
private String jwtSecret;
@Value("${app.jwtExpirationInMs}")
private int jwtExpirationInMs;
public String generateToken(Authentication authentication) {
UserPrincipal userPrincipal = (UserPrincipal) authentication.getPrincipal();
Date now = new Date();
Date expiryDate = new Date(now.getTime() + jwtExpirationInMs);
return Jwts.builder()
.setSubject(Long.toString(userPrincipal.getId()))
.setIssuedAt(new Date())
.setExpiration(expiryDate)
.signWith(SignatureAlgorithm.HS512, jwtSecret)
.compact();
}
public Long getUserIdFromJwt(String token) {
Claims claims = Jwts.parser()
.setSigningKey(jwtSecret)
.parseClaimsJws(token)
.getBody();
return Long.parseLong(claims.getSubject());
}
public boolean validateToken(String authToken) {
try {
Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(authToken);
return true;
} catch (SignatureException ex) {
logger.error("Invalid JWT signature");
} catch (MalformedJwtException ex) {
logger.error("Invalid JWT token");
} catch (ExpiredJwtException ex) {
logger.error("Expired JWT token");
} catch (UnsupportedJwtException ex) {
logger.error("Unsupported JWT token");
} catch (IllegalArgumentException ex) {
logger.error("JWT claims string is empty");
}
return false;
}
}
```
### UserPrincipal.java
```java
public class UserPrincipal implements UserDetails {
private Long id;
private String username;
private String password;
private Collection<? extends GrantedAuthority> authorities;
public UserPrincipal(Long id, String username, String password, Collection<? extends GrantedAuthority> authorities) {
this.id = id;
this.username = username;
this.password = password;
this.authorities = authorities;
}
public static UserPrincipal create(User user) {
List<GrantedAuthority> authorities = user.getRoles().stream().map(role ->
new SimpleGrantedAuthority(role.getName().name())
).collect(Collectors.toList());
return new UserPrincipal(
user.getId(),
user.getUsername(),
user.getPassword(),
authorities
);
}
public Long getId() {
return id;
}
@Override
public String getUsername() {
return username;
}
@Override
public String getPassword() {
return password;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return authorities;
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
```
### UserRepository.java
```java
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByUsername(String username);
Boolean existsByUsername(String username);
Boolean existsByEmail(String email);
}
```
### User.java
```java
@Entity
@Table(name = "users", uniqueConstraints = {
@UniqueConstraint(columnNames = {
"username"
}),
@UniqueConstraint(columnNames = {
"email"
})
})
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotBlank
@Size(max = 40)
private String name;
@NotBlank
@Size(max = 15)
private String username;
@NaturalId
@NotBlank
@Size(max = 40)
@Email
private String email;
@NotBlank
@Size(max = 100)
private String password;
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "user_roles",
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "role_id"))
private Set<Role> roles = new HashSet<>();
public User() {}
public User(String name, String username, String email, String password) {
this.name = name;
this.username = username;
this.email = email;
this.password = password;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
}
```
### Role.java
```java
@Entity
@Table(name = "roles")
public class Role {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Enumerated(EnumType.STRING)
@NaturalId
@Column(length = 60)
private RoleName name;
public Role() {}
public Role(RoleName name) {
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public RoleName getName() {
return name;
}
public void setName(RoleName name) {
this.name = name;
}
}
```
### RoleName.java
```java
public enum RoleName {
ROLE_USER,
ROLE_ADMIN
}
```
### LoginRequest.java
```java
public class LoginRequest {
private String username;
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
```
### JwtAuthenticationResponse.java
```java
public class JwtAuthenticationResponse {
private String accessToken;
public JwtAuthenticationResponse(String accessToken) {
this.accessToken = accessToken;
}
public String getAccessToken() {
return accessToken;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
}
```
## 数据库表
### users 表
| Column Name | Data Type | Description |
|-------------|-------------|------------------------|
| id | bigint | 主键 |
| name | varchar(40) | 姓名 |
| username | varchar(15) | 用户名(唯一) |
| email | varchar(40) | 电子邮件(唯一) |
| password | varchar(100)| 密码 |
### roles 表
| Column Name | Data Type | Description |
|-------------|-------------|------------------------|
| id | bigint | 主键 |
| name | varchar(60) | 角色名称(USER/ADMIN) |
### user_roles 表
| Column Name | Data Type | Description |
|-------------|-------------|----------------------------|
| user_id | bigint | users表的主键 |
| role_id | bigint | roles表的主键 |
阅读全文