问题描述
请问有人可以指导testcafe如何通过IAP安全服务/应用进行身份验证吗?我已尝试阅读本指南here,但对我来说似乎有点复杂。如果有人在此之前做过,那么可以分享也很好。预先谢谢你。
解决方法
我们通过使用google-auth-library并在Testcafe中扩展RequestHook
来实现它。
- 您需要拥有Google IAP凭据(步骤1和2) link)以获取JWT令牌。
- 获得JWT令牌后,就添加它
作为您对应用程序执行的每个请求的授权标头
(通过扩展
RequestHook
实现)。
帮助函数的代码大致如下:
import { RequestHook } from 'testcafe';
import { GoogleAuth } from 'google-auth-library';
export class GoogleIapJWTAuthorization extends RequestHook {
constructor () {
// No URL filtering applied to this hook
// so it will be used for all requests.
super();
const auth = new GoogleAuth({
credentials: serviceGoogleAccount
});
console.log('Google Authentication');
console.log(`Loaded Service Account ${GoogleAccount.client_email}`);
auth.getClient()
.then(client => client.fetchIdToken(`${GoogleAccount.targetAudience}`))
.then(token => {
console.log(`Successfully authenticated with Identity Aware Proxy. Id Token: ${token}`);
this._token = token;
return token;
})
.catch(err => {
console.log(`Identity Aware Proxy Authentication Failed. Id Token: ${token}`);
console.log(JSON.stringify(err));
process.exitCode = 1;
});
}
getGoogleJwtToken() {
return this._token;
}
onRequest (e) {
//Authorization header for authentication into Google Auth IAP
e.requestOptions.headers['Authorization']= `Bearer ${this._token}`;
}
onResponse (e) {
// This method must also be overridden,// but you can leave it blank.
}
}