springboot + vue 写token
时间: 2023-08-04 18:10:04 浏览: 83
使用 Spring Boot 和 Vue.js 实现 token 验证的步骤如下:
1. 在 Spring Boot 后端实现 token 的生成和验证逻辑。
创建一个 TokenUtil 类,用于生成和验证 token。可以使用 Java JWT(jjwt)库来简化操作。
```java
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.springframework.stereotype.Component;
import javax.crypto.SecretKey;
import java.util.Date;
@Component
public class TokenUtil {
private static final String SECRET_KEY = "your_secret_key_here";
private static final long EXPIRATION_TIME = 86400000; // 过期时间设置为一天
// 生成 token
public String generateToken(String userId) {
SecretKey key = Keys.hmacShaKeyFor(SECRET_KEY.getBytes());
return Jwts.builder()
.setSubject(userId)
.setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
.signWith(key)
.compact();
}
// 验证 token
public boolean validateToken(String token) {
try {
SecretKey key = Keys.hmacShaKeyFor(SECRET_KEY.getBytes());
Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token);
return true;
} catch (Exception e) {
return false;
}
}
// 获取 token 中的用户ID
public String getUserIdFromToken(String token) {
SecretKey key = Keys.hmacShaKeyFor(SECRET_KEY.getBytes());
Claims claims = Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token).getBody();
return claims.getSubject();
}
}
```
2. 在 Spring Boot 的控制器中添加 token 相关的接口。
创建一个 UserController 类,用于处理用户相关的请求。
```java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api")
public class UserController {
@Autowired
private TokenUtil tokenUtil;
@PostMapping("/login")
public String login(@RequestBody User user) {
// 验证用户登录逻辑,验证通过后生成 token
if (authenticate(user.getUsername(), user.getPassword())) {
String token = tokenUtil.generateToken(user.getUsername());
return token;
} else {
return "Invalid credentials";
}
}
@GetMapping("/user")
public String getUserInfo(@RequestHeader("Authorization") String token) {
// 验证 token 的有效性,并返回用户信息
if (tokenUtil.validateToken(token)) {
String userId = tokenUtil.getUserIdFromToken(token);
// 根据 userId 获取用户信息并返回
return "User: " + userId;
} else {
return "Invalid token";
}
}
private boolean authenticate(String username, String password) {
// 用户登录验证逻辑
// 返回 true 表示验证通过,返回 false 表示验证失败
// 这里只做演示,实际情况需要根据实际业务逻辑进行验证
return username.equals("admin") && password.equals("password");
}
}
```
3. 在 Vue.js 前端发送登录请求,并使用获取到的 token 发送其他请求。
使用 axios 发送登录请求,并将获取到的 token 存储到浏览器的 localStorage 中。
```javascript
import axios from 'axios'
const login = (username, password) => {
return axios.post('/api/login', { username, password })
.then(response => {
const token = response.data
localStorage.setItem('token', token)
})
}
```
在其他需要验证身份的请求中,将存储的 token 添加到请求的头部 Authorization 中。
```javascript
import axios from 'axios'
const getUserInfo = () => {
const token = localStorage.getItem('token')
const config = {
headers: { 'Authorization': token }
}
return axios.get('/api/user', config)
.then(response => {
const userInfo = response.data
return userInfo
})
}
```
这样,在发送请求时,后端会验证传递的 token 的有效性,并根据需要执行相应的逻辑。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)