我正在谷歌云平台上开发一个带有 JWT 身份验证的应用程序。服务器端我通过 Cloud API Gateway 将身份验证添加到云运行后端。现在我正在创建一个客户端来生成 JWT 令牌并将其传递给调用。为此,我正在创建一个必须部署在 CloudRun 上的应用程序,并且我正在关注以下文档:https ://cloud.google.com/api-gateway/docs/authenticate-service-account#making_an_authenticated_request 。我的问题是我不知道如何指示它需要什么作为 saKeyfile。我试图只将文件名放在 src/main/resources/filetest.json 下,但是一旦我尝试调用该方法,它就会告诉我找不到文件。我也试图指出完整的路径。谁能帮我?
PS我正在使用Java
编辑:这是我的代码,与文档相同
public void makeCall() {
String fullPath="src/main/resources/TEST1-id.json";
String saEmail="testsa@projectID.iam.gserviceaccount.com";
String audience="auth";
int expiryLenght=600;
String token;
try {
token=generateJwt(fullPath,saEmail,audience,expiryLenght);
System.out.println("Token generated: "+token);
URL url = new URL("apigatewayurl");
makeJwtRequest(token, url);
System.out.println("Call performed");
} catch (IOException e) {
e.printStackTrace();
}
}
private static String generateJwt(final String saKeyfile, final String saEmail,
final String audience, final int expiryLength)
throws FileNotFoundException, IOException {
Date now = new Date();
Date expTime = new Date(System.currentTimeMillis() + TimeUnit.SECONDS.toMillis(expiryLength));
// Build the JWT payload
JWTCreator.Builder token = JWT.create()
.withIssuedAt(now)
// Expires after 'expiraryLength' seconds
.withExpiresAt(expTime)
// Must match 'issuer' in the security configuration in your
// swagger spec (e.g. service account email)
.withIssuer(saEmail)
// Must be either your Endpoints service name, or match the value
// specified as the 'x-google-audience' in the OpenAPI document
.withAudience(audience)
// Subject and email should match the service account's email
.withSubject(saEmail)
.withClaim("email", saEmail);
// Sign the JWT with a service account
FileInputStream stream = new FileInputStream(saKeyfile);
ServiceAccountCredentials cred = ServiceAccountCredentials.fromStream(stream);
RSAPrivateKey key = (RSAPrivateKey) cred.getPrivateKey();
Algorithm algorithm = Algorithm.RSA256(null, key);
return token.sign(algorithm);
}
我尝试使用示例中的完整路径并且仅使用 /TEST1-id.json
这里有项目结构。是一个 springboot 应用程序,我将在云运行中部署