我正在尝试找到一种创建JWT并使用服务帐户的私钥对其进行签名的方法,在请求中将签名的JWT发送到Google API端点。我已经搜索出了许多可用于Java和Python的库,但是有没有可用于PHP的库?
将需要遵循Google的Cloud Endpoints标准来进行服务之间的身份验证。下面有一个我们如何访问Java的示例,我想在PHP中完成它?
public 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);
GoogleCredential cred = GoogleCredential.fromStream(stream);
RSAPrivateKey key = (RSAPrivateKey) cred.getServiceAccountPrivateKey();
Algorithm algorithm = Algorithm.RSA256(null, key);
return token.sign(algorithm);
}
使用PHP创建对Google端点的身份验证请求
对于PHP来说似乎不是一个好的解决方案,因为Google的Cloud文档没有提供它,如您所见here。
尽管如此,还是有一些文档,关于如何通过JWT的客户端在Cloud Endpoints中使用PHP,您可以看到here,也可以看到here。
如果这些都不满足您的需求,您可以随时use a custom method to authenticate users。如您所知,要对用户进行身份验证,客户端应用程序必须在HTTP请求的授权标头中向您的后端API发送JSON Web令牌(JWT)。
因此,您可以使用Extensible Service Proxy (ESP):
可扩展服务代理(ESP)代表您的API验证令牌,因此您不必在API中添加任何代码来处理身份验证。但是,您需要配置您的API支持您选择的身份验证方法的OpenAPI文档。
您可以看到如何为用户here.实施自定义方法身份验证。
最后,如果您有兴趣,我link可以与Cloud Endpoints服务一起使用的其他一些身份验证方法,以防上述情况都不适合您的需求。
希望对您有帮助。