Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
通过独立应用程序(而不是Web应用程序)使用JWT在Java中发出刷新令牌请求_Java_Google Analytics_Google Oauth_Google Authentication_Jwt - Fatal编程技术网

通过独立应用程序(而不是Web应用程序)使用JWT在Java中发出刷新令牌请求

通过独立应用程序(而不是Web应用程序)使用JWT在Java中发出刷新令牌请求,java,google-analytics,google-oauth,google-authentication,jwt,Java,Google Analytics,Google Oauth,Google Authentication,Jwt,关于使用JWT获取谷歌分析的刷新令牌,我有一个问题 请参考下面的示例代码,该代码运行良好,我能够获取分析对象,使用该对象我能够访问分析数据 GoogleCredential credentialGA = new GoogleCredential.Builder().setTransport(httpTransport) .setJsonFactory(JSON_FACTORY) .setServiceAccountI

关于使用JWT获取谷歌分析的刷新令牌,我有一个问题

请参考下面的示例代码,该代码运行良好,我能够获取分析对象,使用该对象我能够访问分析数据

        GoogleCredential credentialGA = new GoogleCredential.Builder().setTransport(httpTransport)
                .setJsonFactory(JSON_FACTORY)
                .setServiceAccountId("$#$@#$#$#$@developer.gserviceaccount.com")
                .setServiceAccountScopes(Collections.singleton(AnalyticsScopes.ANALYTICS_READONLY))
                .setServiceAccountPrivateKeyFromP12File(new File("$#$#$%$%$%$-privatekey.p12"))
                .build();
        this.analytics = new Analytics.Builder(httpTransport, JSON_FACTORY, credentialGA).setApplicationName("Demo App").build();
如果我调用credentialGA.getAccessToken()它将返回一个字符串。但是调用credentialGA.getRefreshToken()它总是返回null。 现在,正如谚语所说,如果我必须使用这个分析对象进行进一步的调用,我需要使用刷新令牌,我可以再次创建GoogleCredential对象来获取分析对象

因此,在遵循中提到的步骤之后,我创建了一个JWT。然后,该JWT将用于进行刷新令牌调用。 此链接上共享的示例解释了如何通过servlet/jsp/http实现这一点。

是否有任何示例代码可以解释使用Java Standalone app使用JWT实现相同的刷新令牌调用任务

提前谢谢

问候,, 普拉塔梅斯

生成JWT的代码:

    private final static Charset UTF8_CHARSET = Charset.forName("UTF-8");
private static KeyStore myStore = null;
private static FileInputStream in_cert = null;
public static void main(String[] args) {
    PrivateKey privateKey = null;       
    try {
        in_cert = new FileInputStream(
                "D://Google Analytics//ClientLogin//Analytics//%#$%#$%$^%^%$&^%&$-privatekey.p12");

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    try {
        myStore = KeyStore.getInstance("PKCS12");
        myStore.load(in_cert, "notasecret".toCharArray());

        Enumeration<String> aliases = myStore.aliases();
        String alias = "";       
        Enumeration objEnumeration = myStore.aliases();
        while (objEnumeration.hasMoreElements() == true) {
            alias = (String) objEnumeration.nextElement();

            privateKey = (PrivateKey) myStore.getKey(alias,
                    "notasecret".toCharArray());
            if(privateKey != null){
            System.out.println("PRIVATE KEY:" + privateKey.toString());
            }
        }

    } catch (Exception e1) {
        e1.printStackTrace();
    }

    JsonObject header = new JsonObject();
    header.addProperty("alg", "RS256");
    header.addProperty("typ", "JWT");
    String headerStr = header.toString();

    JsonObject claim = new JsonObject();
    claim.addProperty("iss", "%^@%@^%$%@developer.gserviceaccount.com");
    claim.addProperty("scope", "https://www.googleapis.com/auth/devstorage.readonly");
    claim.addProperty("aud", "https://accounts.google.com/o/oauth2/token");
    claim.addProperty("exp", "1384497516");
    claim.addProperty("iat", "1384597516");     
    String claimStr = claim.toString();

    try {

        byte[] headerArr = headerStr.getBytes(UTF8_CHARSET);
        System.out.println(Base64.encodeBase64String(headerArr));
        byte[] claimArr = claimStr.getBytes(UTF8_CHARSET);
        System.out.println(Base64.encodeBase64String(claimArr));
        String inputStr = Base64.encodeBase64String(headerArr) + "." + Base64.encodeBase64String(claimArr);         
        Signature signature = Signature.getInstance("SHA256withRSA");
        signature.initSign(privateKey);
        signature.update(inputStr.getBytes(UTF8_CHARSET));      

    } catch (Exception e) {
        e.printStackTrace();
    }
private final static Charset UTF8_Charset=Charset.forName(“UTF-8”);
私有静态密钥库myStore=null;
_cert中的私有静态FileInputStream=null;
公共静态void main(字符串[]args){
PrivateKey PrivateKey=null;
试一试{
in\u cert=新文件输入流(
“D://Google Analytics//ClientLogin//%Analytics/%#$%#$%$^%^%&^%&$-privatekey.p12”);
}catch(filenotfounde异常){
e、 printStackTrace();
}
试一试{
myStore=KeyStore.getInstance(“PKCS12”);
加载(在证书“notasecret.toCharArray()中);
枚举别名=myStore.alias();
字符串别名=”;
枚举对象=myStore.alias();
while(objEnumeration.hasMoreElements()==true){
别名=(字符串)objEnumeration.nextElement();
privateKey=(privateKey)myStore.getKey(别名,
“notasecret”;
if(privateKey!=null){
System.out.println(“私钥:+privateKey.toString());
}
}
}捕获(异常e1){
e1.printStackTrace();
}
JsonObject头=新的JsonObject();
header.addProperty(“alg”、“RS256”);
标题。添加属性(“典型”、“JWT”);
字符串headerStr=header.toString();
JsonObject声明=新的JsonObject();
claim.addProperty(“iss”,“%^@%@^%$%@developer.gserviceaccount.com”);
claim.addProperty(“范围”)https://www.googleapis.com/auth/devstorage.readonly");
索赔。添加财产(“澳元”https://accounts.google.com/o/oauth2/token");
索赔.addProperty(“exp”,“1384497516”);
索赔.addProperty(“iat”、“1384597516”);
String claimStr=claim.toString();
试一试{
字节[]headerArr=headerStr.getBytes(UTF8\u字符集);
System.out.println(Base64.encodeBase64String(headerArr));
byte[]rr=claimStr.getBytes(UTF8\u字符集);
System.out.println(Base64.encodeBase64String(rr));
字符串输入str=Base64.encodeBase64String(headerArr)+“+”+Base64.encodeBase64String(headerArr);
Signature=Signature.getInstance(“SHA256withRSA”);
signature.initSign(私钥);
signature.update(inputStr.getBytes(UTF8_字符集));
}捕获(例外e){
e、 printStackTrace();
}
然后复制此JWT字符串并在另一个程序员中使用,以请求刷新令牌,如下所示:

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost("<link i have posted in the comment>");
    try {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("grant_type",
                "urn:ietf:params:oauth:grant-type:jwt-bearer"));
        nameValuePairs.add(new BasicNameValuePair("assertion",
                "<JWT Calculated earlier>"));
        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = client.execute(post);
        BufferedReader rd = new BufferedReader(new InputStreamReader(
                response.getEntity().getContent()));

        String line = "";
        while ((line = rd.readLine()) != null) {
            System.out.println(line);
            if (line.startsWith("Auth=")) {
                String key = line.substring(5);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
HttpClient=newdefaulthttpclient();
HttpPost=新的HttpPost(“”);
试一试{
List nameValuePairs=新的ArrayList(1);
添加(新的BasicNameValuePair(“授权类型”,
“urn:ietf:params:oauth:grant-type:jwt-bearer”);
添加(新的BasicNameValuePair(“断言”),
""));
setEntity(新的UrlEncodedFormEntity(nameValuePairs));
HttpResponse response=client.execute(post);
BufferedReader rd=新的BufferedReader(新的InputStreamReader(
response.getEntity().getContent());
字符串行=”;
而((line=rd.readLine())!=null){
系统输出打印项次(行);
if(line.startsWith(“Auth=)){
字符串键=行。子字符串(5);
}
}
}捕获(IOE异常){
e、 printStackTrace();
}

成功的API调用实际上需要一个访问令牌。对于服务帐户,您可以通过使用私钥对JWT签名并将其发送到accounts.google.com来获得访问令牌

看起来上面的代码应该可以很好地完成这项工作

刷新令牌是另一回事。最终用户授权您的应用程序访问其数据后,谷歌将向您的应用程序提供刷新令牌。与上面的私钥类似,刷新令牌可用于获取访问令牌,然后用于后续API调用


简单地说,对于服务帐户用例(代码段显示的内容),您根本不需要看到刷新令牌。您具体想做什么?

我认为您可以通过调用

https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={accessToken} 

endpoint并再次创建JWT并获取accessToken。

我正在寻找示例代码,该代码可以为我提供创建JWT并使用此JWT发送刷新令牌请求的概述。我尝试了相同的操作。我无法获取任何示例来验证我的工作。不幸的是,google也没有足够的文档或示例。如果我试着运行我的代码,我得到了{“error”:“invalid_request”}我想说的是,不可能使用JWT获取刷新令牌。私钥+JWT和刷新令牌都是获取访问令牌的方法,这最终是创建AP所需的