lundi 9 novembre 2020

TestCafe authentication to IAP secured test environment with application that has Bearer token based user authentication

Our test environment is behind Google IAP and the application under test is using Bearer tokens for user authentication.

In order to access the test environment, I am getting the Google JWT token and then adding it as Authorization header on all requests by extending the RequestHook:

import { RequestHook } from 'testcafe';
import config from '../config/.config.json';
import serviceGoogleAccount from '../config/.service-google-account.json';

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 ${serviceGoogleAccount.client_email}`);
    auth.getClient()
    .then(client => client.fetchIdToken(`${config.googleAuthSettings.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.
  }
}

When testing manually and logging into Google account in order to access the test environment, this token is set as a cookie:

Cookie example set by Google IAP after logging in

So far, so good.

The problem occurs when I am trying to login into application with a user. Our identity endpoint returns Bearer token for a user and in order to access user specific pages I need to pass this user's Bearer token as Authorization header on requests.

But due to above Google JWT token implementation the Authorization Header is already in use. And because after login into application I am getting 401 Unauthorized for pages/endpoints that require user's Bearer token, I presume that the user's Bearer token is getting overwritten by Google JWT token above.

Is there any way to solve this?

As far as I understand setting the cookie is not that straight forward according to https://github.com/DevExpress/testcafe/issues/4063

Aucun commentaire:

Enregistrer un commentaire