在C#中从Google Container Registry获取图像清单

时间:2018-07-29 08:20:01

标签: c# google-cloud-platform

我尝试使用以下代码获取清单:

string json = File.ReadAllText(jsonKeyFilePath);
//Console.WriteLine(json);
JsonCredentialParameters jcp = JsonConvert.DeserializeObject<JsonCredentialParameters>(json);
List<string> scopes = new List<string>() { "https://www.googleapis.com/auth/cloud-platform.read-only" };
ServiceAccountCredential.Initializer initializer = new ServiceAccountCredential.Initializer(jcp.ClientEmail)
{
    Scopes = scopes
};

initializer = initializer.FromPrivateKey(jcp.PrivateKey);
ServiceAccountCredential sac = new ServiceAccountCredential(initializer);     
sac.RequestAccessTokenAsync(CancellationToken.None).GetAwaiter().GetResult();
string clientId = "2769402fjknsfdbnmx.apps.googleusercontent.com";
var jwtBasedAccessToken = CreateAccessToken(sac, clientId);

var req = new GoogleAssertionTokenRequest()
{
    Assertion = jwtBasedAccessToken
};

var result = req.ExecuteAsync(sac.HttpClient,
    sac.TokenServerUrl, CancellationToken.None,
    sac.Clock).Result;

string token = result.IdToken;

string uri = "https://gcr.io/myproject/v2/hello-world2/manifests/latest";

var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
string response = httpClient.GetStringAsync(uri).Result;
Console.WriteLine("response = {0}", response);

在上面的代码中,jsonKeyFilePath是ServiceAccount凭据的路径,如下所示:

{
    "type": "service_account",
    "project_id": "containerimageinfoproject",


    "private_key_id": "123myprivatekeyid456",
    "private_key": "-----BEGIN PRIVATE KEY-----\nMIIE....UYU=\n-----END PRIVATE KEY-----\n",
    "client_email": "xyz@myproject.iam.gserviceaccount.com",
    "client_id": "104946695288383039395",
    "auth_uri": "https://accounts.google.com/o/oauth2/auth",
    "token_uri": "https://accounts.google.com/o/oauth2/token",
    "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
    "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/imageinformation%40myproject.iam.gserviceaccount.com"
}

但是我得到的响应是登录页面的html。有没有一种方法可以绕过登录页面并以编程方式获取图像清单而无需用户交互?

谢谢, 坦维尔

0 个答案:

没有答案