Token的生成和檢驗


package TestToken;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.junit.Test;

import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class TokenTest {

    //公共密鑰客戶端不會知道
    public static String SECRET="FreeMaNong";

    public static  String  createToken() throws UnsupportedEncodingException {
        //簽名發布時間
        Date iatDate=new Date();
        System.out.println(iatDate);//英文時間

        //設置簽名過期時間  1分鍾
        Calendar nowTime=Calendar.getInstance();
        nowTime.add(Calendar.MINUTE,1);
        Date expiresDate=nowTime.getTime();
        //System.out.println(expiresDate);

        Map<String,Object> map=new HashMap<String, Object>();
        map.put("alg","HS256");//設置算法 為HS256
        map.put("typ","JWT");//設置類型為JWT
        String token=JWT.create().withHeader(map)
                .withClaim("name","Free碼農")
                .withClaim("age","28")
                .withClaim("org","今日頭條")
                .withClaim("username","chenyu")
                .withIssuedAt(iatDate)//設置簽發時間
                .withExpiresAt(expiresDate)//設置過去時間 過期時間大於簽發時間
                .sign(Algorithm.HMAC256(SECRET));//用公共密鑰加密
       //System.out.println(token);
       return token;
    }

    public static Map<String,Claim> verifyToken(String token) throws UnsupportedEncodingException {
        JWTVerifier verifier =JWT.require(Algorithm.HMAC256(SECRET)).build();//用公共密鑰解密驗證
        DecodedJWT jwt=null;
        try{
            jwt=verifier.verify(token);
        }catch (Exception e)
        {
            throw new RuntimeException("登錄憑證已過去,請重新登錄");
        }
        return jwt.getClaims();
    }


    @Test
    public void TestToken() throws UnsupportedEncodingException {
        String token=createToken();
        System.out.println("Token:"+token);
        Map<String,Claim> claims=verifyToken(token);
        System.out.println(claims.get("name").asString());
        System.out.println(claims.get("age").asString());
        System.out.println(claims.get("username").asString());
        System.out.println(claims.get("org")==null?null:claims.get("org").asString());

        //測試過期token
//        String GuoQiToken="eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJhdXRoMCJ9.izVguZPRsBQ5Rqw6dhMvcIwy8_9lQnrO3vpxGwPCuzs";
//        Map<String,Claim> claims2=verifyToken(GuoQiToken);
    }



    @Test
    public void Test() throws UnsupportedEncodingException {
        Algorithm algorithm = Algorithm.HMAC256("secret");
        String token = JWT.create().withIssuer("auth0") .sign(algorithm);
        System.out.println(token);
    }
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM