Fork me on GitHub

Spring Boot之JWT小工具类

添加依赖

dependencies {
    compile group: 'com.google.code.gson', name: 'gson', version: '2.8.6'
    compile group: 'io.jsonwebtoken', name: 'jjwt-api', version: '0.10.7'
    runtime group: 'io.jsonwebtoken', name: 'jjwt-impl', version: '0.10.7'
    runtime group: 'io.jsonwebtoken', name: 'jjwt-orgjson', version: '0.10.7'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    testImplementation('org.springframework.boot:spring-boot-starter-test') {
        exclude group: 'org.junit.vintage', module: 'junit-vintage-engine'
    }
}

创建JwtUtils.java

import com.google.gson.Gson;
import com.icodesoft.rsa.domain.Payload;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.joda.time.DateTime;

import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.Base64;
import java.util.UUID;

public class JwtUtils {

    private static final String JWT_PAYLOAD_KEY = "key";

    /**
     * 生成JWT token
     *
     * @param userInfo   载荷中数据
     * @param privateKey PrivateKey object
     * @param expire     过期时间(m)
     * @return
     */
    public static String generateTokenExpireInMinutes(Object data, PrivateKey privateKey, int expire) {
        return Jwts.builder()
                .claim(JWT_PAYLOAD_USER_KEY, new Gson().toJson(data))
                .setId(createJTI())
                .setExpiration(DateTime.now().plusMinutes(expire).toDate())
                .signWith(privateKey, SignatureAlgorithm.RS256)
                .compact();
    }

    /**
     * 获取token中的用户信息
     *
     * @param token     用户请求中的令牌
     * @param publicKey 公钥
     * @return
     */
    public static <T> Payload<T> getInfoFromToken(String token, PublicKey publicKey, Class<T> claz) {
        Jws<Claims> claimsJws = parserToken(token, publicKey);
        Claims body = claimsJws.getBody();
        Payload<T> payload = new Payload<>();
        payload.setId(body.getId());
        payload.setUserInfo(new Gson().fromJson(body.get(JWT_PAYLOAD_KEY).toString(), claz));
        payload.setExpiration(body.getExpiration());
        return payload;
    }
    
    /**
     * 解析JWT token
     *
     * @param token     jwt token
     * @param publicKey PublicKey
     * @return
     */
    private static Jws<Claims> parserToken(String token, PublicKey publicKey) {
        return Jwts.parser().setSigningKey(publicKey).parseClaimsJws(token);
    }

    private static String createJTI() {
        return new String(Base64.getEncoder().encode(UUID.randomUUID().toString().getBytes()));
    }
}
posted @ 2020-12-08 18:04  逍遥メ风  阅读(341)  评论(0编辑  收藏  举报