Reputation: 253
I'm developing a web API that uses the google drive API, on my local machine, first run it redirected me to a google page to authenticate and then worked fine. Now I want to publish my code to Azure, and after I've published it the same function fails, because I could authenticate. How do I perform this authentication on the server?
I've followed the .NET QuickStart (https://developers.google.com/drive/api/v3/quickstart/dotnet), here is my code:
using (var stream =
new FileStream($@"{dir}\client_secret.json", FileMode.Open, FileAccess.Read))
{
var cred = GoogleClientSecrets.Load(stream).Secrets;
Credentials = GoogleWebAuthorizationBroker.AuthorizeAsync(
cred,
Scopes,
"user",
CancellationToken.None).Result;
}
service = new DriveService(new BaseClientService.Initializer()
{
HttpClientInitializer = Credentials,
ApplicationName = ApplicationName,
});
}
Upvotes: 0
Views: 1661
Reputation: 117281
The tutorial you are following is for a .NET console application this is a native application not a web application. GoogleWebAuthorizationBroker
is for use with installed applications. It works on localhost because its able to spawn the browser window on your machine. This wont work in a hosted environment because it cant spawn a web browser on the server.
You should be following this example Web applications
using System;
using System.Web.Mvc;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Auth.OAuth2.Flows;
using Google.Apis.Auth.OAuth2.Mvc;
using Google.Apis.Drive.v2;
using Google.Apis.Util.Store;
namespace Google.Apis.Sample.MVC4
{
public class AppFlowMetadata : FlowMetadata
{
private static readonly IAuthorizationCodeFlow flow =
new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = new ClientSecrets
{
ClientId = "PUT_CLIENT_ID_HERE",
ClientSecret = "PUT_CLIENT_SECRET_HERE"
},
Scopes = new[] { DriveService.Scope.Drive },
DataStore = new FileDataStore("Drive.Api.Auth.Store")
});
public override string GetUserId(Controller controller)
{
// In this sample we use the session to store the user identifiers.
// That's not the best practice, because you should have a logic to identify
// a user. You might want to use "OpenID Connect".
// You can read more about the protocol in the following link:
// https://developers.google.com/accounts/docs/OAuth2Login.
var user = controller.Session["user"];
if (user == null)
{
user = Guid.NewGuid();
controller.Session["user"] = user;
}
return user.ToString();
}
public override IAuthorizationCodeFlow Flow
{
get { return flow; }
}
}
}
Note about azure you may have to change the location where filedatastore stores the credentials it depends upon where you have write access to. That can be done by supplying a path to the folder you want to store it in.
new FileDataStore(@"c:\datastore",true)
Upvotes: 1