简体   繁体   English

在Java中使用标头,有效负载和签名创建JWT

[英]creating JWT with header, payload and signature in java

i want to generate a jwt for a given header, payload and a secret key. 我想为给定的头,有效负载和密钥生成一个jwt。

my header; 我的头

{ "typ": "JWT", "alg": "HS256" } {“ typ”:“ JWT”,“ alg”:“ HS256”}

my payload; 我的有效载荷;

{ "iss": "46181382", "ist": "project", "iat": 1536225835, "exp": 1536226835, "jti": "abcdefghi" } {“ iss”:“ 46181382”,“ ist”:“ project”,“ iat”:1536225835,“ exp”:1536226835,“ jti”:“ abcdefghi”}

my secret key; 我的秘密钥匙; 105446462291847624638651561dfg156148df941819498 105446462291847624638651561dfg156148df941819498

here is my java code, it already create an jwt. 这是我的Java代码,它已经创建了一个jwt。 but i think the secret key is not get included to it. 但我认为秘密密钥并未包含在内。 because once i use that jwt for my header in tokbox api call i get the following response. 因为一旦我在tokbox api调用中使用该jwt作为我的标头,就会得到以下响应。

 {
"code": -1,
"message": "Invalid signature",
"description": "Invalid signature"
}

here is the code; 这是代码;

    byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary("105446462291847624638651561dfg156148df941819498");
    Key signingKey = new SecretKeySpec(apiKeySecretBytes, SignatureAlgorithm.HS256.getJcaName());

    Map map = new HashMap<String,Object>();
    map.put("alg","HS256");
    map.put("typ","JWT");

    String jwt = Jwts.builder()
            .setHeader(map)
            .claim("iss", "46181382")
            .claim("ist", "project")
            .claim("iat", currentTimeSeconds())
            .claim("exp", expireTimeSeconds())
            .claim("jti", "abcdefghi")
            .signWith(SignatureAlgorithm.HS256,signingKey)
            .compact();

currentTimeSeconds() and expireTimeSeconds() are methods written by myself. currentTimeSeconds()和expireTimeSeconds()是我自己编写的方法。 i am sure there is no issue with them. 我确定他们没有问题。 I am not sure with this .signWith() method. 我不确定此.signWith()方法。

Could any one please help me. 谁能帮我。

Thank you. 谢谢。

I found the answer. 我找到了答案。 In the above code the secret key should be given as Base64URL encoded value. 在上面的代码中,密钥应作为Base64URL编码的值给出。 it means the first line should change as follows. 这意味着第一行应更改如下。

byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary("MTA1NDQ2NDYyMjkxODQ3NjI0NjM4NjUxNTYxZGZnMTU2MTQ4ZGY5NDE4MTk0OTg=");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM