SpringSecurity+JWT
依赖
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
<version>2.6.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
<version>2.6.3</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>5.6.1</version>
</dependency>
yaml配置文件
jwt:
data:
SECRET: jwt-token-secret
tokenHeader: Authorization
expiration: 604800
tokenHead: Bearer
JWTUtil
package com.example.jwtutil.utils;
import com.example.jwtutil.entity.User;
import io.jsonwebtoken.*;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@Component
@Data
@ConfigurationProperties("jwt.data")
@Slf4j
public class JWTUtil {
private static final String CLAIM_KEY_USERNAME = "subject";
private static final String CLAIM_KEY_CREATED = "created";
private String SECRET;
private Long expiration;
public String createToken(UserDetails userDetails) {
HashMap<String, Object> claims = new HashMap<>();
claims.put(CLAIM_KEY_USERNAME, userDetails.getUsername());
claims.put(CLAIM_KEY_CREATED, new Date());
return createToken(claims);
}
public String getUsernameFromToken(String token) {
String username = "";
try {
Claims claims = getClaimsFromToken(token);
username = claims.getSubject();
} catch (Exception e) {
username = null;
log.info("error:{}", "用户名未能获取 from token");
}
return username;
}
private Claims getClaimsFromToken(String token) {
Claims claims = null;
try {
claims = Jwts.parser()
.setSigningKey(SECRET)
.parseClaimsJws(token)
.getBody();
} catch (ExpiredJwtException e) {
e.printStackTrace();
} catch (UnsupportedJwtException e) {
e.printStackTrace();
} catch (MalformedJwtException e) {
e.printStackTrace();
} catch (SignatureException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
return claims;
}
private String createToken(Map<String, Object> claims) {
return Jwts.builder()
.setClaims(claims)
.setExpiration(expirationDate())
.signWith(SignatureAlgorithm.ES512, SECRET)
.compact();
}
private Date expirationDate() {
return new Date(System.currentTimeMillis() + expiration * 1000);
}
public boolean validateToken(String token, UserDetails userDetails) {
String username = getUsernameFromToken(token);
return username.equals(userDetails.getUsername()) && !isTokenExpired(token);
}
private boolean isTokenExpired(String token) {
Date expiredDate = getExpiredDateFeomToken(token);
return expiredDate.before(new Date());
}
private Date getExpiredDateFeomToken(String token) {
Claims claims = getClaimsFromToken(token);
return claims.getExpiration();
}
public boolean canBeRefreshed(String token){
return !isTokenExpired(token);
}
public String refreshToken(String token){
Claims claims = getClaimsFromToken(token);
claims.put(CLAIM_KEY_CREATED,new Date());
return createToken(claims);
}
}
JWT单独简易
前面一些做法是一样的
package cn.sbs.packinggo.utils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import java.util.Calendar;
import java.util.Date;
@Slf4j
@Data
@Component
@ConfigurationProperties("jwt.data")
public class JWTUtils {
public String SECRET;
private String header;
public String createToken(Long userId){
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.SECOND,24*60*60*7);
JwtBuilder builder = Jwts.builder()
.setHeaderParam("typ","JWT")
.setSubject(userId+"")
.setIssuedAt(new Date())
.setExpiration(calendar.getTime())
.signWith(SignatureAlgorithm.HS256,SECRET);
return builder.compact();
}
public Claims parseToken(String token){
try{
return Jwts.parser()
.setSigningKey(SECRET)
.parseClaimsJws(token)
.getBody();
}catch (Exception e){
log.error("jwt match error:{}",e);
return null;
}
}
public boolean judgeTokenExpiration(Date expiration){
return expiration.before(new Date());
}
}
|