基于JAVA+SpringBoot+Vue+uniApp小程序的心理健康测试平台
由于这个问题涉及到的内容较多,且不是特别具体的代码问题,我将提供一个简化的核心函数示例,展示如何在Spring Boot后端使用Spring Security配置JWT认证。
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class JwtTokenUtil {
// 私钥等配置项
private static final String SECRET_KEY = "your-secret-key";
private static final long EXPIRATION_TIME = 3600000; // 1 hour
public String generateToken(UserDetails userDetails) {
Map<String, Object> claims = new HashMap<>();
userDetails.getAuthorities().stream()
.map(GrantedAuthority::getAuthority)
.forEach(authority -> claims.put(authority, true));
return createToken(claims, userDetails.getUsername());
}
private String createToken(Map<String, Object> claims, String subject) {
return Jwts.builder()
.setClaims(claims)
.setSubject(subject)
.setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
.signWith(SignatureAlgorithm.HS512, SECRET_KEY)
.compact();
}
public boolean validateToken(String token, UserDetails userDetails) {
String username = Jwts.parser()
.setSigningKey(SECRET_KEY)
.parseClaimsJws(token)
.getBody()
.getSubject();
return username.equals(userDetails.getUsername()) && !isTokenExpired(token);
}
private boolean isTokenExpired(String token) {
Date expiration = Jwts.parser()
.setSigningKey(SECRET_KEY)
.parseClaimsJws(token)
.getBody()
.getExpiration();
return expiration.before(new Date());
}
publi
评论已关闭