如何使用JJWT和Play Framework Java一起使用JWT?

时间:2018-06-17 23:44:09

标签: jwt jjwt

我正在尝试使用需要使用JWT的Zoom API。我已成功使用node.js生成JWT并调用Zoom API,如下所示:

var jwt = require('jsonwebtoken');
var zoom_key = "abcd";
var zoom_secret = "efgh";
var payload = {
    iss: Zoom_Key,
    exp: ((new Date()).getTime() + 3600)
};

//Automatically creates header, and returns JWT
var token = jwt.sign(payload, zoom_secret);

module.exports = token;

但是,现在我正试图在JAVA中使用相同的方式。当我使用JJWT的令牌时,它总是给出"无效令牌"来自zoom api的错误消息。任何人都可以帮我找出原因吗? 首先,我在Playload.java中创建一个Playload类,如下所示:

// in Playload.java
package palyload;

public class Playload {
    public String iss;

    public Playload(String iss) {
        this.iss = iss;
    }
}

其次, 我导入JJWT和play.libs.Json来生成JWT令牌,如下所示:

package controllers;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import play.libs.Json;
import play.mvc.Controller;
import play.mvc.Result;
import palyload.Playload;


public class JWT extends Controller {

    private static final String zoom_key = "abcd";
    private static final String zoom_secret = "efgh";
    private static final String baseUrl = "https://api.zoom.us/v2/users/?access_token=";

    public String setToken (Object obj) {
        String token = "";
        Map<String, Object> map = new HashMap<>();
        map.put("json", Json.toJson(obj));
        try {
            token = Jwts.builder()
                    .setClaims(map)              
                 .setExpiration(Date.from(ZonedDateTime.now(ZoneId.systemDefault()).plusSeconds(3600).toInstant()))
                    .signWith(SignatureAlgorithm.HS256, zoom_secret)
                    .compact();
        } catch (ArrayIndexOutOfBoundsException e) {
            e.printStackTrace();
        }
        System.out.println(Jwts.parser().setSigningKey(zoom_secret).parseClaimsJws(token).getBody().getSubject().toString());
        // System.out.println(map.toString());
        return token;
    }
    public String getToken () {
        Playload pl = new Playload(zoom_key);
        System.out.println("playload: " + Json.toJson(pl).toString());
        return setToken(pl);
    }
    public String setUrl () {
        return baseUrl + getToken();
    }
    public Result getUrl () {
        return ok(setUrl());
    }
}

不知道为什么这个令牌网址不像Node.js那样正确?

0 个答案:

没有答案