系统找不到使用X509Certificate2指定的文件来连接Azure服务器中的Google OAuth2.0

时间:2015-08-06 14:06:04

标签: c# azure x509certificate2

我正在使用此代码连接到Google OAuth2.0,而我正在使用C#库。

using (var tImpersonationContext = new ImpersonationContext(ConfigurationManager.AppSettings["ImpersonationDomain"], ConfigurationManager.AppSettings["ImpersonationUser"], ConfigurationManager.AppSettings["ImpersonationPassword"]))
{
    string[] tScopes = new string[] { AnalyticsService.Scope.Analytics };
    var tKeyFilePath = Path.Combine(System.IO.Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]), String.Format("GoogleCertificates\\{0}", this.OAuthKeyName));
    var tServiceAccountEmail = this.OAuthServiceAccountEmail;

    //loading the Key file
    var tCertificate = new X509Certificate2(tKeyFilePath, this.OAuthKeyPassword, X509KeyStorageFlags.Exportable);
    var tCredential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(tServiceAccountEmail)
    {
        Scopes = tScopes
    }.FromCertificate(tCertificate));

    if (tCredential.RequestAccessTokenAsync(CancellationToken.None).Result)
    {
        this.SessionToken = tCredential.Token.AccessToken;
    }
}

在我的开发环境中,一切工作都很完美但是当我将App移动到我的Azurre服务器时,我收到了这个错误:

  

系统找不到指定的文件。

当我尝试排除这一行时:

var tCertificate = new X509Certificate2(tKeyFilePath, this.OAuthKeyPassword, X509KeyStorageFlags.Exportable);

我确定路径是正确的,实际上如果我在文件资源管理器中复制并粘贴路径,则导入证书的向导就会启动。

我确信模仿是有效的,因为线路已经完成了。

我试图将其更改为:

var tCertificate = new X509Certificate2(tKeyFilePath, this.OAuthKeyPassword, X509KeyStorageFlags.MachineKeySet);

或者这个:

var tCertificate = new X509Certificate2(tKeyFilePath, this.OAuthKeyPassword, X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.UserKeySet | X509KeyStorageFlags.UserProtected | X509KeyStorageFlags.DefaultKeySet);

没有任何工作,事实上,我从本网站的其他问题尝试的所有内容都无效。

如果有帮助的是我假装在计划任务中使用的Windows应用程序,则从Google Analytics获取数据。

有人知道为什么不在Azure服务器上工作吗?

提前致谢。

更新

我已尝试安装证书,我已将代码更改为:

var tCertificate = new X509Certificate2(tKeyFilePath, this.OAuthKeyPassword, X509KeyStorageFlags.MachineKeySet);

但现在我有这个错误:

  

密钥无法在指定状态下使用。

1 个答案:

答案 0 :(得分:0)

我已将所有代码更改为aproach,现在正在运行。

首先,您必须在证书下的受信任根证书颁发机构内的MMC管理器中安装证书,并且必须将其设置为本地计算机。

然后你只需要使用这段代码:

X509Store tCertStore = new X509Store(StoreName.Root, StoreLocation.LocalMachine);
tCertStore.Open(OpenFlags.ReadOnly);
X509Certificate2Collection tCertCollection = tCertStore.Certificates.Find(X509FindType.FindByThumbprint, this.OAuthKeyFingerprint, false);

// Get the first cert with the thumbprint
if (tCertCollection.Count > 0)
{
    // header
    var tHeader = new { typ = "JWT", alg = "RS256" };

    // claimset
    var tTimes = GetExpiryAndIssueDate();
    var tClaimset = new
    {
        iss = this.OAuthServiceAccountEmail,
        scope = "https://www.googleapis.com/auth/analytics",
        aud = "https://www.googleapis.com/oauth2/v3/token",
        iat = tTimes[0],
        exp = tTimes[1],
    };

    JavaScriptSerializer ser = new JavaScriptSerializer();

    // encoded header
    var tHeaderSerialized = ser.Serialize(tHeader);
    var tHeaderBytes = Encoding.UTF8.GetBytes(tHeaderSerialized);
    var tHeaderEncoded = Convert.ToBase64String(tHeaderBytes);

    // encoded claimset
    var tClaimsetSerialized = ser.Serialize(tClaimset);
    var tClaimsetBytes = Encoding.UTF8.GetBytes(tClaimsetSerialized);
    var tClaimsetEncoded = Convert.ToBase64String(tClaimsetBytes);

    // input
    var tInput = tHeaderEncoded + "." + tClaimsetEncoded;
    var tInputBytes = Encoding.UTF8.GetBytes(tInput);

    X509Certificate2 tCertificate = tCertCollection[0];

    // signiture
    var tRSA = tCertificate.PrivateKey as RSACryptoServiceProvider;

    var tCspParam = new CspParameters
    {
        KeyContainerName = tRSA.CspKeyContainerInfo.KeyContainerName,
        KeyNumber = tRSA.CspKeyContainerInfo.KeyNumber == KeyNumber.Exchange ? 1 : 2,
        Flags = CspProviderFlags.UseMachineKeyStore
    };
    var tAesCsp = new RSACryptoServiceProvider(1024, tCspParam) { PersistKeyInCsp = true };
    var tSignatureBytes = tAesCsp.SignData(tInputBytes, "SHA256");
    var tSignatureEncoded = Convert.ToBase64String(tSignatureBytes);

    // jwt
    var tJWT = tHeaderEncoded + "." + tClaimsetEncoded + "." + tSignatureEncoded;

    HttpClient tClient = new HttpClient();

    Dictionary<string, string> tPost = new Dictionary<string, string>
        {
            {"assertion", tJWT},
            {"grant_type", "urn:ietf:params:oauth:grant-type:jwt-bearer"}
        };

    FormUrlEncodedContent tContent = new FormUrlEncodedContent(tPost);

    var tURI = "https://www.googleapis.com/oauth2/v3/token";

    HttpResponseMessage tResult = tClient.PostAsync(tURI, tContent).Result;
    TokenResponse tTokenObject = JsonConvert.DeserializeObject<TokenResponse>(tResult.Content.ReadAsStringAsync().Result);

    this.SessionToken = tTokenObject.access_token;
}

tCertStore.Close();

我希望这有助于某人。

快乐的编码。