简体   繁体   中英

Google calendar api v3 authorization and authentication with C#

Hello people I can`t find working code (C#) for google calendar api v3 authorization and authentication? Looks like all posts too old and library made changes, anyone got working code? I registered project to google developers and got credentials for usage. Thanks.

Here is a static method to get the CalendarService object used to execute all requests, you will need to store the JSON file that you downloaded from the Google Developers Dashboard somewhere within your project and then reference it in the code below.

The first time you run this you will be redirected to a Google login screen in your web browser and will be prompted to give access to your calendar there. Once you have confirmed then the below will create a credentials file which will be stored in a location you specify on the user's computer (for example your application's installation directory). From then on the stored credentials file will be used and you won't need to login again.

public static CalendarService GetService()
    {
        var Scopes = new string[] { CalendarService.Scope.Calendar };

        UserCredential credential;
        string filePath = Path.Combine("*YOUR DOWNLOADED JSON FILE LOCATION HERE*");

        using (var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
        {
            string credPath = "*WHERE YOU WILL STORE YOUR CREDENTIALS FILE*";

            credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
                GoogleClientSecrets.Load(stream).Secrets,
                Scopes,
                "user",
                CancellationToken.None,
                new FileDataStore(credPath, true)).Result;
        }

        // Create Google Calendar API service.
        var service = new CalendarService(new BaseClientService.Initializer()
        {
            HttpClientInitializer = credential,
            ApplicationName = "*YOUR APPLICATION NAME HERE*",
        });

        return service;
    }

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