0

EDIT: This is my final code after taking your(@DalmTo) advice:

  public static AnalyticsService Authenticate()
    { 
        string[] scopes = new string[] { AnalyticsService.Scope.Analytics,                 
     AnalyticsService.Scope.AnalyticsManageUsers};    

        string keyFilePath = @"G:\PleskVhosts\mydomainname\httpdocs\App_Data\API Project-2f74017ed363.p12";    // found in developer console
        string serviceAccountEmail = "myconsoleapiaccount@developer.gserviceaccount.com";  // found in developer console

        var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable);
        ServiceAccountCredential credential = new ServiceAccountCredential(new ServiceAccountCredential.Initializer(serviceAccountEmail) { Scopes = scopes }.FromCertificate(certificate));

        AnalyticsService service = new AnalyticsService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = "myappname",
        });

Thank you so much for the tutorial you linked me, I examined it carefully and your code was so much less work than trying to do it manually. I am aware of the tips you have given me, and I have necessary permissions for that account in my Google Analytics account. I followed your tutorial, and it works like a charm in my localhost, but when I publish my website, this is the current error I am getting this error:

{"Message":"Access is denied.\r\n","StackTrace":" at System.Security.Cryptography.X509Certificates.X509Store.Add(X509Certificate2 certificate)\r\n at Thunder.Main.Default.Authenticate()\r\n at Thunder.Main.Default.GetChartData()","ExceptionType":"System.Security.Cryptography.CryptographicException"}

I have contacted with my hosting provider, and they are telling me that they won't be making changes in IIS, I've added trust level full tag to the web.config, but I am still getting this error.I am currently working on it, but if you have any advices, please let me know. I will update here If I can come up with a solution. Thanks!

  • 1
    This is most likely a permissions issue.You need to go to My (assuming installed there) and manage the permissions on it (the cert), giving the correct permissions to the appropriate app account. For other ways, info: http://stackoverflow.com/questions/425688/how-to-set-read-permission-on-the-private-key-file-of-x-509-certificate-from-ne – Mike Cheel May 16 '15 at 02:30
  • Hi @MikeCheel , thank you very much for your fast answer. I indeed found that article, may I ask if you are referring to that post or the codeproject one? http://www.codeproject.com/script/Forums/View.aspx?fid=1649&msg=2062983 – TC Seden Ergül May 16 '15 at 02:45
  • There are numerous ways to add permissions to the cert like utilities or code. You should just pick what works best for your situation. I think the most important part to keep in mind is that you can only manage the keys in the My store. – Mike Cheel May 16 '15 at 02:46
  • Oh, I understand, thanks. But I don't use My store in my project, I am just using this certificate to get google analytics data. I edited my post with all of the data I am using to authenticate. Can I still implement those permission methods you have sent a link to? – TC Seden Ergül May 16 '15 at 02:52
  • I still this is related to permissions on the key (or there is no key at all and that is why). Certs have a lot of things to look for. – Mike Cheel May 16 '15 at 02:54
  • I feel like its a permission problem aswell, and having no access to IIS makes it even worse, but I am not sure how to give permission to it. I am sorry if asking too many questions, it is my first time using certs , and my research hit a dead end – TC Seden Ergül May 16 '15 at 02:59
  • Look how they are doing it in the code project article. Basically windows stores the keyfile as an actual filr in that rsa folder. The actual container has a guid like name. The code project code attempts to locate and set the permissions. – Mike Cheel May 16 '15 at 03:01
  • Ok, so I have examined their method, and implemented it with my code, I've updated the post with my current code. I am using PlaceInStore method after I create the key, but unfortunately I am still getting the same error. Have I done something wrong? – TC Seden Ergül May 16 '15 at 03:33
  • Is it finding the key when you step through the code? – Mike Cheel May 16 '15 at 10:12
  • I have put both errors that I am getting on localhost and hosting environment to my post. I think it still doesn't find it even though its there. – TC Seden Ergül May 16 '15 at 20:11
  • I STILL think its permissions. Are you right acciunt? – Mike Cheel May 16 '15 at 20:20
  • I know that its permissions too, but isn't that method in codeproject should have surpassed it? I am using the right account with Environment.Username. I have contacted my hosting server about changing settings in IIS, but they refused to do it because its a shared hosting – TC Seden Ergül May 16 '15 at 20:25
  • you realize in the Authenticate() method you have keyfile name hard coded and its not the same dir as you have in the variable at the top? Also why not use Googles client library for this? – Linda Lawton - DaImTo May 18 '15 at 06:47
  • HI @DalmTo, yes I am aware of that, I've changed it and the file location after I saw the topic about it in stackoverflow, they were just writing the file's name like that. I came across to this tutorial while I was searching for a way to intergrate google analytics data to my website, I don't know about google's client library. If you can point me to a direction for it, I can give it a try:) Thanks! – TC Seden Ergül May 18 '15 at 18:27

2 Answers2

1

As mentioned above you need to configure IIS but as our case, some time you need to check the permission of the following folder:

C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys

If you set X509KeyStorageFlags parameter it will create a key file in this folder. In my case there was a difference in permission of this folder. Pool account was not added in the mentioned folder.

Shani
  • 53
  • 6
  • Appreciate your answer - saved me a bunch of time trying to troubleshoot access denied error loading .pfx. – Zach Jan 28 '22 at 13:43
0

You really are making things harder for yourself here. I am not sure whats wrong with your code. TBH I have never tried doing it manually because I use the client library

NuGet Package

PM> Install-Package Google.Apis.Analytics.v3

Authentication with a service account.

You need to send the full path to the key file or sometimes it complains. Ideally it should be out side of the web root but it needs to be someplace that the webserver has access to read it since you are using asp for this.

string[] scopes = 
      new string[] { 
         AnalyticsService.Scope.Analytics,                 // view and manage your Google Analytics data
         AnalyticsService.Scope.AnalyticsManageUsers};     // View Google Analytics data      

string keyFilePath = @"c:\file.p12" ;    // found in developer console
string serviceAccountEmail = "xx@developer.gserviceaccount.com";  // found in developer console
//loading the Key file
var certificate = new X509Certificate2(keyFilePath, "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(serviceAccountEmail)
                                       {Scopes = scopes }.FromCertificate(certificate));

Creating Service

You pass the credential created above to the service. All of your requests will then go though the service.

AnalyticsService service = new AnalyticsService(new BaseClientService.Initializer()
            {
             HttpClientInitializer = credential,
             ApplicationName = "Analytics API Sample",
            });

Tips

  1. For a service account to work with Google Analytics it must have access to your Google Analytics account. Go to the Google Analytics website admin section create a new user at the account level it must be the account level. Did I mention it wont work if it isn't the account level.
  2. Code is taken from my tutorial series. Google Analtics with C# enjoy
Linda Lawton - DaImTo
  • 106,405
  • 32
  • 180
  • 449
  • Hi @DalmTo, thank you so much for your answer. I updated my question with your latest version of your code, please take a look. Thanks! – TC Seden Ergül May 19 '15 at 21:51