jwt生成token

jwt官网:https://jwt.io/

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import org.junit.Assert;
import org.junit.Test;

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

/*
 *
 * @author maduar
 * @date 02/07/2018 10:18 AM
 * @email maduar@163.com
 *
 * */
public class JWTTest {

  @Test
  public void test() throws UnsupportedEncodingException {

    // 1. create head
    Map<String, Object> headerClaims = new HashMap();
    headerClaims.put("alg", "HS256");
    headerClaims.put("typ", "JWT");

    try {
      // 2. create signture
      Algorithm algorithm = Algorithm.HMAC256("secret");
      String token = JWT.create()
          .withHeader(headerClaims)
          .withClaim("sub", "1234567890") // 2. create playload
          .withClaim("name", "John Doe") // 2. create playload
          .withClaim("admin", true) // 2. create playload
          .sign(algorithm);

      String result = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ";

      Assert.assertEquals(token, result);

    } catch (JWTCreationException exception){
      //Invalid Signing configuration / Couldn't convert Claims.
      exception.printStackTrace();
    }
  }
}

  

posted @ 2018-07-02 16:43  金色元年  阅读(352)  评论(0编辑  收藏  举报