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

本文关键字:连接 Google 文件 OAuth2 X509Certificate2 服务器 Azure 系统 找不到 | 更新日期: 2023-09-27 18:06:45

我正在使用此代码连接到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;
    }
}

在我的开发环境中,一切工作都很完美,但当我将应用程序移动到我的Azure服务器时,我得到了这个错误:

系统找不到指定的文件。

当我尝试执行这一行时:

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应用程序,我假装在一个任务计划中使用,从谷歌分析获取数据。

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

提前感谢。

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

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

但是现在我得到这个错误:

密钥不能在指定状态下使用。

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

我已经改变了所有的代码和方法,现在正在工作。

首先,您必须在受信任的根证书颁发机构的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();

我希望这对某人有帮助。

快乐编码。