项目导入了<groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId>依赖,为什么没有JwtTokenUtil类?
时间: 2023-07-09 22:33:00 浏览: 110
`spring-boot-starter-security`依赖提供了Spring Security的基础集成,但是并没有提供`JwtTokenUtil`类。如果您想要使用`JwtTokenUtil`,您需要手动添加相关的依赖库或者自行定义该类。以下是一个示例`JwtTokenUtil`类的实现:
```java
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Function;
@Component
public class JwtTokenUtil {
private final Key key;
public JwtTokenUtil(@Value("${jwt.secret}") String secret) {
this.key = Keys.hmacShaKeyFor(secret.getBytes());
}
public String generateToken(UserDetails userDetails) {
Map<String, Object> claims = new HashMap<>();
return createToken(claims, userDetails.getUsername());
}
public String extractUsername(String token) {
return extractClaim(token, Claims::getSubject);
}
public Date extractExpiration(String token) {
return extractClaim(token, Claims::getExpiration);
}
public <T> T extractClaim(String token, Function<Claims, T> claimsResolver) {
final Claims claims = extractAllClaims(token);
return claimsResolver.apply(claims);
}
private Claims extractAllClaims(String token) {
return Jwts.parserBuilder().setSigningKey(key).build().parseClaimsJws(token).getBody();
}
private String createToken(Map<String, Object> claims, String subject) {
final Date now = new Date();
final Date validity = new Date(now.getTime() + 1000 * 60 * 60); // 1 hour validity
return Jwts.builder().setClaims(claims).setSubject(subject).setIssuedAt(now)
.setExpiration(validity).signWith(key, SignatureAlgorithm.HS256).compact();
}
public boolean validateToken(String token, UserDetails userDetails) {
final String username = extractUsername(token);
return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
}
private boolean isTokenExpired(String token) {
final Date expiration = extractExpiration(token);
return expiration.before(new Date());
}
}
```
这个示例类使用了`io.jsonwebtoken`类库来生成和解析JWT令牌。如果您想要使用该类,您需要在`pom.xml`文件中添加以下依赖:
```
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
```
同时,您需要在`application.properties`或`application.yaml`文件中定义JWT的密钥:
```properties
jwt.secret=your-secret-key
```
请注意,这只是一个示例实现,您可以按照您的需求对其进行修改。
阅读全文