Aditya kumar
Aditya kumar

Reputation: 33

.NET gmail API Authentication (without user interaction)

I am trying to authneticate gmail api using c# console application. I am using.net sdk of Google api and the code i am using to authorize the api is as follows :

UserCredential credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
new ClientSecrets
{
    ClientId = "clientId",
    ClientSecret = "clientsecret"
},
 new[] {  GmailService.Scope.GmailModify },
"user",
 CancellationToken.None, null);

But the above code open a browser window to ask for permission to access the service, I need to avoid this authentication activity as I need to schedule ".exe" file of the project on Azure

Upvotes: 2

Views: 1853

Answers (1)

Vishnu Prasad V
Vishnu Prasad V

Reputation: 1258

You're confusing between authorization and authentication.

Authorization is a one time process and you cannot authorize without user authorizing your app to do whatever you're meaning to do. It is a one time process.

What you're doing in the code is authorization. It will definitely open a browser for the user to authorize your app. Once you authorize your app, then for next time, all you need to do is authenticate. Authentication doesn't require this manual user process.

All you have to do is to use the UserCredential you receive from the Google from the next time you need it.

Store the credential you receive from the service somewhere and use it next time to initialize the Service

var service = new GmailService(new BaseClientService.Initializer()
{
    HttpClientInitializer = credential, //your stored credential
    ApplicationName = "App",
});

However you may need to refresh the Credential token (which expires every 60 minutes). It should automatically refresh, but you can refresh it manually everytime you need it by making a check.

if (credential.Token.IsExpired)
    var returnBool = await credential.RefreshTokenAsync(cancellationToken);

Upvotes: 2

Related Questions