java JWT

来源:互联网 发布:淘宝直播刷粉丝软件 编辑:程序博客网 时间:2024/05/29 16:36

直接上自己最后调试的代码吧

参考地址:https://github.com/auth0/java-jwt


package com.rayclear.common;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.rayclear.util.StringUtil;

import net.sf.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
/**
 * JWT操作类
 * @author zhoushuai
 *
 */
public class JWTManager {
    
    //使用平台提供的secret
    private static  String JWT_SECRET;
    
    private static  Logger LOGGER = LoggerFactory.getLogger(JWTManager.class);
    
    static{
        ResourceBundle bundle = PropertyResourceBundle.getBundle("application");  
        JWT_SECRET  = bundle.getString("JWT_SECRET");
    }
    
    /**
     * 构建JWT的示例方法
     * @param id
     * @param ttlMillis
     * @return
     */
    public static String createJWT(String id,long ttlMillis) {
        String token = null;
        long nowMillis = System.currentTimeMillis();
        try {
            Algorithm algorithm = Algorithm.HMAC256(JWT_SECRET);
            //我们添加过期
            long expMillis = nowMillis + ttlMillis;
            
            Date iatDate = new Date(nowMillis);
            Date expDate = new Date(expMillis);
            token = JWT.create()
                    .withClaim("user_id", id)
                    .withExpiresAt(expDate)
                    .withIssuedAt(iatDate)
                    .sign(algorithm);
            
        } catch (UnsupportedEncodingException exception){
            //UTF-8 编码不支持异常
            exception.printStackTrace();
        } catch (JWTCreationException exception){
            //无效的签名配置/无法转换
            exception.printStackTrace();
        }
        return token;
    }
    /**
     * 解码和验证Token码
     * @param jwt
     */
    public static JSONObject parseJWT(HttpServletRequest request) {
        JSONObject json = null;
        try {
            String token = "";
            String authorization = request.getHeader("Authorization");
            String authentication = request.getHeader("Authentication");
            if(StringUtil.isNull(authorization)&&StringUtil.isNull(authentication)){
                LOGGER.info("无效的请求!");
                throw new RuntimeException();
            }else{
                token = StringUtil.isNull(authorization)?authentication:authorization;
            }
            Algorithm algorithm = Algorithm.HMAC256(JWT_SECRET);
            JWTVerifier verifier = JWT.require(algorithm)
                .build();
            DecodedJWT jwt = verifier.verify(token);
            String payload = jwt.getPayload();
            byte[] base64 = Base64.decodeBase64(payload);
            String jsonStr = new String(base64);
            //转json对象
            json = JSONObject.fromObject(jsonStr);
            
            LOGGER.info("ID: {}", json.get("user_id"));
            LOGGER.info("exp: {}",json.get("exp"));
            LOGGER.info("iat: {}", json.get("iat"));
            
        } catch (UnsupportedEncodingException exception){
            LOGGER.info("认证失败 :UTF-8 encoding not supported");
            exception.printStackTrace();
        } catch (JWTVerificationException exception){
            LOGGER.info("认证失败 :Invalid signature/claims");
            exception.printStackTrace();
        }
        return json;
    }
}


原创粉丝点击