在前后端交互时,首先由客户端发送用户的登录凭证到服务器,然后服务器进行验证,验证成功后服务器返回一个包含加密后的访问令牌(access token)和刷新令牌(refresh token)的响应。客户端拿到这些令牌后存储在本地,以便之后的每次请求都带上这些令牌用来访问需要认证的API。这个过程中,服务器会根据令牌的有效性来确定是否让客户端操作API。以下是一个基于Spring Boot框架和JWT的代码示例:
前端代码:
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
username: 'your_username',
password: 'your_password'
})
}).then(res => res.json())
.then(data => {
//存储access_token和refresh_token到本地
localStorage.setItem('access_token', data.access_token);
localStorage.setItem('refresh_token', data.refresh_token);
});
后端代码:
@Component
public class JwtTokenProvider {
private final String JWT_SECRET = "your_jwt_secret";
@Value("${jwt.expiration.time}")
private Long JWT_EXPIRATION_TIME;
public String generateToken(Authentication authentication) {
User user = (User) authentication.getPrincipal();
Date now = new Date();
Date expiryDate = new Date(now.getTime() + JWT_EXPIRATION_TIME);
String userId = Long.toString(user.getId());
Map claimsMap = new HashMap<>();
claimsMap.put("id", (Long.toString(user.getId())));
claimsMap.put("username", user.getUsername());
claimsMap.put("fullName", user.getFullName());
return Jwts.builder()
.setSubject(userId)
.addClaims(claimsMap)
.setIssuedAt(now)
.setExpiration(expiryDate)
.signWith(SignatureAlgorithm.HS512, JWT_SECRET)
.compact();
}
public
上一篇:AppDelegate中pushviewController没有显示
下一篇:AppDependencies 表消耗大量的 GB,因为 MS.ProcessedByMetricExtractors。