我正在尝试使用JWT连接到Google的REST API(用于Google日历)。我已经按照指示进行操作,直到here为止。当我通过JWT发送发帖请求时(以前的StackOverflow帖子的正文中带有grant_type
和assertion
),我得到一个错误:
{
"error": "invalid_grant",
"error_description": "Invalid JWT: Failed audience check. The right audience is https://www.googleapis.com/oauth2/v4/token"
}
我的代码简短,因此我将在下面完整地发布(没有私人详细信息)。我正在使用jaguar_jwt
库,并根据其示例代码对JWT生成进行了建模。我已经创建了一个服务帐户,并且相信会一直遵循所有说明,直到Google文档中的上述要点为止。
import 'package:http/http.dart' as http;
import 'package:jaguar_jwt/jaguar_jwt.dart';
String generateJWT() {
final String privateKey = "-----BEGIN PRIVATE KEY-----.********=\n-----END PRIVATE KEY-----\n";
final claimSet = new JwtClaim(
issuer: 'google-api@**********.iam.gserviceaccount.com',
audience: <String>['https://www.googleapis.com/oauth2/v4/token'],
otherClaims: <String,dynamic>{
"scope":"https://www.googleapis.com/auth/calendar",
"access_type": "offline"
},
maxAge: const Duration(minutes: 60));
String token = issueJwtHS256(claimSet, privateKey);
// print(token);
return token;
}
void sendJWT(String jwt) async {
var client = new http.Client();
try {
String googleUri = "https://www.googleapis.com/oauth2/v4/token";
var requestBody = {'grant_type':'urn:ietf:params:oauth:grant-type:jwt-bearer',
'assertion':'$jwt',
"access_type": "offline"
};
await client.post(googleUri, body: requestBody)
.then((value) => print(value.body));
} finally {
client.close();
}
}
main(List<String> arguments) {
sendJWT(generateJWT());
}