简体   繁体   中英

Google API authentification Server-Side

I'm trying to use the Gmail API reading the emails, but I'm running into the problem that I want to do a server-side authentification but with all the examples from google Doc., he always shows me window asking me to add my credentials (Gmail & password).

public static async void CreateService()
    {
        GoogleCredential credential;
        using (var stream = new FileStream(@"key.json", FileMode.Open, 
FileAccess.Read))
        {
            credential = GoogleCredential.FromStream(stream)
                .CreateScoped(GmailService.Scope.GmailLabels, 
GmailService.Scope.GmailModify, GmailService.Scope.GmailMetadata, 
GmailService.Scope.GmailReadonly);
        }
        var service = new GmailService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = "Gmail",
        });
        Console.WriteLine(ListMessages(service, "me", ""));
    }

Then I got this code from the documentation of the google api of how to read the messages from a user.

public static List<Message> ListMessages(GmailService service, String userId, String query)
            {
                List<Message> result = new List<Message>();
                UsersResource.MessagesResource.ListRequest request = service.Users.Messages.List(userId);
                request.Q = query;
                do
                {
                    try
                    {
                        ListMessagesResponse response = request.Execute();
                        result.AddRange(response.Messages);
                        request.PageToken = response.NextPageToken;
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("An error occurred: " + e.Message);
                    }
                } while (!String.IsNullOrEmpty(request.PageToken));

                return result;
            }

But when I run it I get this error: An error occurred:

Google.Apis.Requests.RequestError
Bad Request [400]
Errors [
        Message[Bad Request] Location[ - ] Reason[failedPrecondition] Domain[global]
]

Answer:

If you want to use a user as the authentication account, then no. This is not possible and you will always get a login window pop-up.

Other Methods:

You can however create and use a service account to impersonate your user and bypass the need for authenticating on run. They require a little extra set up but you can create them in the Google Developer Admin Console .

Code Example:

After creating your service account and giving it the roles and permissions it needs (see links below), you only need to make small edits to your code to use it instead of your regular account. This is an example in Python, but you can find other examples on the managing keys page :

import os

from google.oauth2 import service_account
import googleapiclient.discovery

def create_key(service_account_email):
    """Creates a key for a service account."""

    credentials = service_account.Credentials.from_service_account_file(
        filename=os.environ['GOOGLE_APPLICATION_CREDENTIALS'],
        scopes=['YOUR SCOPES HERE'])

    # Rememer here that your credentials will need to be downloaded 
    # for the service account, YOU CAN NOT USE YOUR ACCOUNT'S CREDENTIALS!
    service = googleapiclient.discovery.build(
        'service', 'version', credentials=credentials)

    key = service.projects().serviceAccounts().keys().create(
        name='projects/-/serviceAccounts/' + service_account_email, body={}
        ).execute()

    print('Created key: ' + key['name'])

I hope this is helpful to you!

References:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM