import com.izouma.awesomeadmin.util.PropertiesFileLoader;
import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.GenericXmlContextLoader;
import org.springframework.transaction.annotation.Transactional;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

@RunWith(value = SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/spring/applicationContext.xml"}, loader = GenericXmlContextLoader.class)
@Transactional
public class AppTokenTest {
    @Test
    public void genKey() {
        SecretKey key = Keys.hmacShaKeyFor(Base64.getDecoder().decode(PropertiesFileLoader.getProperties("jwtsecret").getBytes()));

        System.out.println(new String(Base64.getEncoder().encode(key.getEncoded())));
    }

    @Test
    public void genToken() {
        SecretKey key = Keys.hmacShaKeyFor(Base64.getDecoder().decode(PropertiesFileLoader.getProperties("jwtsecret").getBytes()));

        long currentTimeMillis = System.currentTimeMillis();// 当前时间戳
        JwtBuilder jwt = Jwts.builder();
        jwt.setId(UUID.randomUUID().toString())
                .setIssuer("admin")
                .setIssuedAt(new Date(currentTimeMillis))
                .setSubject("84664")
//                .setExpiration()
                .signWith(key);
        System.out.println(jwt.compact());
    }

    @Test
    public void parseToken() {
        SecretKey key = Keys.hmacShaKeyFor(Base64.getDecoder().decode(PropertiesFileLoader.getProperties("jwtsecret").getBytes()));
        Jwt jwt = Jwts.parser()
                .setSigningKey(key)
                .parse("eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIxMDZjNzU5OS1kNmRhLTQ5ODUtOWQ5MS0" +
                        "4ZGZmOWY3MzAwNWMiLCJpc3MiOiJhZG1pbiIsImlhdCI6MTUzMzYzNTQyNSwic3ViI" +
                        "joiODQ2NjQifQ.tqKdEXle3S29Ruaj_9EPpfi7NMvM1_I05eUuGTi1fUU");
        Claims claims = (Claims) jwt.getBody();

        System.out.println(jwt);
    }

}
