Google OAuth Api not redirecting on Login - google-api

I try to authenticate my user using Google authentication services
When i run this code on local server its working fine (It redirects to google login and after successful login its hit call back on redirectPath).
But when publish this code on Production server then its not working.
When I debug this code, I found its redirect and open the google login page on hosted environment(Where application is published).
here is my code - Please help
string redirecrPath = "http://localhost:1212/Admin/YouTubeIntegration/Success";
UserCredential credential;
using (var stream = new FileStream(Server.MapPath("/XmlFile/client_secrets.json"), FileMode.Open, FileAccess.Read))
{
GoogleAuth.RedirectUri = redirecrPath;
credential = await GoogleAuth.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
new[] { YouTubeService.Scope.Youtube, YouTubeService.Scope.YoutubeReadonly, YouTubeService.Scope.YoutubeUpload },
"user",
CancellationToken.None,
new FileDataStore(this.GetType().ToString())
);
}
Please let me know if you need more information.
Thanks in Advance

The code to login from a web page is not the same as the code to login with an installed application. Installed applications can spawn the login screen directly on the current machine. If you tried to do that on a webserver it wouldnt work the following is the code for using web login
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; }
}
}
}
copied from here

Related

Unable to add service account to a site added in google search console via an API

TLDR version
Is there an API to do this - https://support.google.com/webmasters/answer/7687615?hl=en, I want to be able to map service account to user using some API, (I am able to do it manually, but the list is long)
Long version
From what I understand there are 2 types of users
Type 1 - Normal user (human) logging in and using google search console
Type 2 - Google service accounts, used by application to pull data
Now I want to add several hundreds of site in Google Search Console, I found C# clients/API to do that.
I am able to add/list sites using normal user account using API, and then verify by using UI to see them getting added.
I am able (no error returned) to add/list sites using service accounts using API, but then unable to
see service account user being added in the user list of the site. But I still see the site when I call the list api
when pulling data for this site, I get errors
Google.Apis.Requests.RequestError
User does not have sufficient permission for site 'https://www.example.com/th-th/city/'. See also: https://support.google.com/webmasters/answer/2451999. [403]
Errors [Message[User does not have sufficient permission for site 'https://www.example.com/th-th/city/'. See also: https://support.google.com/webmasters/answer/2451999.] Location[ - ] Reason[forbidden] Domain[global]
It points me to this link - https://support.google.com/webmasters/answer/7687615?visit_id=1621866886080-4412438468466383489&rd=2 where I can use the UI and manually add my service account and then everything works fine.
But I want to do the same thing via API, because I will be having hundreds of sites to add to.
Please advice on how to go about this one?
Seems like this user also had similar problem, but no solution - How to connect Google service account with Google Search Console
CODE
This is the code I use to create site using normal user and client id/secret, here if I create a site I am able to see it on UI but the API (https://developers.google.com/webmaster-tools/search-console-api-original/v3/sites/add) does not have option to use service account.
public class WebmastersServiceWrapper
{
private string user = "realemail#example.com";
private readonly ClientSecrets _clientSecrets = new ClientSecrets
{
ClientId = "example.apps.googleusercontent.com",
ClientSecret = "example"
};
private readonly string[] _scopes = {
WebmastersService.Scope.WebmastersReadonly,
WebmastersService.Scope.Webmasters
};
public async Task<WebmastersService> GetWebmastersService()
{
var credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(_clientSecrets, _scopes, user, CancellationToken.None);
var service = new WebmastersService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "WebMasters API Sample",
});
return service;
}
}
public class WebMasterSiteService
{
private readonly WebmastersServiceWrapper _connection;
public WebMasterSiteService()
{
_connection = new WebmastersServiceWrapper();
}
public async Task<IEnumerable<string>> GetSites()
{
var service = await _connection.GetWebmastersService();
var sitesResponse = await service.Sites.List().ExecuteAsync();
return SiteMapper.MapSites(sitesResponse);
}
public async Task DeleteSite(string site)
{
var service = await _connection.GetWebmastersService();
var response = await service.Sites.Delete(site).ExecuteAsync();
return;
}
public async Task AddSite(string site)
{
var service = await _connection.GetWebmastersService();
var response = await service.Sites.Add(site).ExecuteAsync();
return;
}
}
Here is the piece of code where I create sites using service worker, it gets created somewhere (as when I call list I get it back) but when I query that site using other APIs it fails with this error
Google.Apis.Requests.RequestError
User does not have sufficient permission for site 'https://www.example.com/th-th/city/'. See also: https://support.google.com/webmasters/answer/2451999. [403]
Errors [
Message[User does not have sufficient permission for site 'https://www.example.com/th-th/city/'. See also: https://support.google.com/webmasters/answer/2451999.] Location[ - ] Reason[forbidden] Domain[global]
]
public class SearchConsoleServiceWrapper
{
private readonly string[] _scopes = {
SearchConsoleService.Scope.WebmastersReadonly,
SearchConsoleService.Scope.Webmasters
};
public SearchConsoleService GetWebmastersService()
{
using var stream = new FileStream("key-downloaded-from-console-cloud-google.json", FileMode.Open, FileAccess.Read);
var credential = GoogleCredential.FromStream(stream)
.CreateScoped(_scopes)
.UnderlyingCredential as ServiceAccountCredential;
return new SearchConsoleService(new BaseClientService.Initializer
{
HttpClientInitializer = credential
});
}
}
public class SiteService
{
private readonly SearchConsoleServiceWrapper _connection;
public SiteService()
{
_connection = new SearchConsoleServiceWrapper();
}
public async Task<IEnumerable<string>> GetSites()
{
var service = _connection.GetWebmastersService();
var sitesResponse = await service.Sites.List().ExecuteAsync();
return SiteMapper.MapSites(sitesResponse);
}
public async Task DeleteSite(string site)
{
var service = _connection.GetWebmastersService();
var response = await service.Sites.Delete(site).ExecuteAsync();
return;
}
public async Task AddSite(string site)
{
var service = _connection.GetWebmastersService();
var response = await service.Sites.Add(site).ExecuteAsync();
return;
}
}
Final thoughts
Maybe I am missing something simple, also I haven't found a way to establish a relationship between my google search console account and my service account. But when I use my service account and add it as a user manually on a site, everything works and I am able to query properly.

Error accessing Google Calendar using OAuth2.0. and service account: "Invalid impersonation prn email address."

I am trying to use Google Calendar API to access the calendar of various users in our organization calendars using OAuth2.0 and a service account but I get an error
"invalid_request" "Invalid impersonation prn email address.".
In the Google console I have:
- Created a project
- Created a service account and enabled "Domain wide delegation" and given the "Project Owner" role, then got a P12 key.
- In Security > Advanced settings > Authentication > Manage API client access I have given the serviceaccount access to https://www.googleapis.com/auth/calendar.readonly.
using System;
using System.Windows.Forms;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Calendar.v3;
using Google.Apis.Services;
using System.Security.Cryptography.X509Certificates;
namespace Google_Calendar
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button2_Click(object sender, EventArgs e)
{
string GoogleCertificate = #"testcalendar-209521-772939e76cae.p12"; // keyfile filename
string GoogleEmail = #"myserviceaccount#testcalendar-209521.iam.gserviceaccount.com"; // serviceaccount mail
string GoogleUser = "MyServiceAccount"; // serviceaccount name
string[] Scopes = new string[] { "https://www.googleapis.com/auth/calendar.readonly" };
X509Certificate2 certificate = new X509Certificate2(GoogleCertificate, "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential( new ServiceAccountCredential.Initializer(GoogleEmail)
{
Scopes = Scopes,
User = GoogleUser
}.FromCertificate(certificate));
CalendarService service = new CalendarService(new BaseClientService.Initializer() { HttpClientInitializer = credential, ApplicationName = "testcalendar" });
string CalenderID = "mathias#mydomain.com";
var CalRequest = service.Events.List(CalenderID);
CalRequest.TimeMin = DateTime.Now.AddMonths(-1); //optional parameter
CalRequest.TimeMax = DateTime.Now.AddMonths(+1); //optional parameter
do
{
var events = CalRequest.Execute(); // here I get the error
foreach (var item in events.Items)
{
// do stuff
}
CalRequest.PageToken = events.NextPageToken;
} while (CalRequest.PageToken != null);
}
}
}
Any ideas what the problem might be? I think the problem is in my settings in Google somewhere. Do I miss a step there?
With some help from Google support I solved the problem(s).
1: Where I had used the service account user
string GoogleUser = "MyServiceAccount";
I should have used an impersonate user
string GoogleUser = "MyAdminUser";
2: When I added the scopes on my Admin Console, I added it by using the Service Account email, which then got translated visually to the ClientID of my Project and everything seemed to be ok. But it was not. When I instead used the ClientID everything worked correct.

Aspnet core web api protected with Azure

I have a web api in my organization built with aspnet core. We want to publish that api to be consumed by an android app, a mvc5 app and an aspnet core mvc6 app. How can I configure the web api in azure so that the apps that consume it don't ask to login. The web apps, are already protected with azure, but when I protect the web api with azure I get a 401 when I make a request to it. I don't know how to configure the app in azure or the code I must configure in the api. I've read a lot but I don't find a way to acomplish this. All I want is to login in my web app, and the web app starts to ask data to the web api through ajax. I should send in the ajax request some sort of bareer token, but i don`t know what config i must do in azure and in the apps. I hope you can help me.
After you protected the web API with Azure AD, we need to send to access token with request for the web API for authorization. And we can get the access token when the users call the web API from web app. Here is the code to acquire the token in the web app for your reference:
public async Task<IActionResult> Index()
{
AuthenticationResult result = null;
List<TodoItem> itemList = new List<TodoItem>();
try
{
string userObjectID = (User.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier"))?.Value;
AuthenticationContext authContext = new AuthenticationContext(Startup.Authority, new NaiveSessionCache(userObjectID, HttpContext.Session));
ClientCredential credential = new ClientCredential(Startup.ClientId, Startup.ClientSecret);
result = await authContext.AcquireTokenSilentAsync(Startup.TodoListResourceId, credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));
//
// Retrieve the user's To Do List.
//
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, TodoListBaseAddress + "/api/todolist");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
HttpResponseMessage response = await client.SendAsync(request);
//
// Return the To Do List in the view.
//
if (response.IsSuccessStatusCode)
{
List<Dictionary<String, String>> responseElements = new List<Dictionary<String, String>>();
JsonSerializerSettings settings = new JsonSerializerSettings();
String responseString = await response.Content.ReadAsStringAsync();
responseElements = JsonConvert.DeserializeObject<List<Dictionary<String, String>>>(responseString, settings);
foreach (Dictionary<String, String> responseElement in responseElements)
{
TodoItem newItem = new TodoItem();
newItem.Title = responseElement["title"];
newItem.Owner = responseElement["owner"];
itemList.Add(newItem);
}
return View(itemList);
}
else
{
//
// If the call failed with access denied, then drop the current access token from the cache,
// and show the user an error indicating they might need to sign-in again.
//
if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized)
{
var todoTokens = authContext.TokenCache.ReadItems().Where(a => a.Resource == Startup.TodoListResourceId);
foreach (TokenCacheItem tci in todoTokens)
authContext.TokenCache.DeleteItem(tci);
ViewBag.ErrorMessage = "UnexpectedError";
TodoItem newItem = new TodoItem();
newItem.Title = "(No items in list)";
itemList.Add(newItem);
return View(itemList);
}
}
}
catch (Exception ee)
{
if (HttpContext.Request.Query["reauth"] == "True")
{
//
// Send an OpenID Connect sign-in request to get a new set of tokens.
// If the user still has a valid session with Azure AD, they will not be prompted for their credentials.
// The OpenID Connect middleware will return to this controller after the sign-in response has been handled.
//
return new ChallengeResult(OpenIdConnectDefaults.AuthenticationScheme);
}
//
// The user needs to re-authorize. Show them a message to that effect.
//
TodoItem newItem = new TodoItem();
newItem.Title = "(Sign-in required to view to do list.)";
itemList.Add(newItem);
ViewBag.ErrorMessage = "AuthorizationRequired";
return View(itemList);
}
//
// If the call failed for any other reason, show the user an error.
//
return View("Error");
}
And below is the code sample which use JwtBearerAppBuilderExtensions to add OpenIdConnect Bearer authentication capabilities to an HTTP application pipeline for the web API to verify the token:
public class Startup
{
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
// Add the console logger.
loggerFactory.AddConsole(LogLevel.Debug);
// Configure the app to use Jwt Bearer Authentication
app.UseJwtBearerAuthentication(new JwtBearerOptions
{
AutomaticAuthenticate = true,
AutomaticChallenge = true,
Authority = String.Format(Configuration["AzureAd:AadInstance"], Configuration["AzureAD:Tenant"]),
Audience = Configuration["AzureAd:Audience"],
});
}
}
The full code sample you can refer here.
Note: to run this sample successfully, we need to modify the Title and Owner to lowercase title, owner in the ToDoController of web app:
foreach (Dictionary<String, String> responseElement in responseElements)
{
TodoItem newItem = new TodoItem();
newItem.Title = responseElement["title"];
newItem.Owner = responseElement["owner"];
itemList.Add(newItem);
}
You can use Azure OpenIdConnect for federated authentication. A good article from microsoft below -
Calling a web API in a web app using Azure AD and OpenID Connect

Reusing Google API credentials in GData API

I am trying to make a web application is ASP.NET MVC 5 with which I can authenticate a user with a Google Account and then read data from his/her spreadsheets stored in Google Drive/Google Sheets.
I am using Google API to authenticate a user. After a user is successfully authenticated, I get the credentials back from Google in an object which is of type Google.Apis.Auth.OAuth2.Web AuthResult.UserCredential
I can then successfully create a service to list files from Drive using code similar to
var driveService = new DriveService(new BaseClientService.Initializer
{
HttpClientInitializer = result.Credential,
ApplicationName = "ASP.NET MVC Sample"
});
Now, I want to use GData API to read content from spreadsheets in Drive. For this to work, I need to have a SpreadsheetsService object and then set it's RequestFactory parameter to an instance of GOAuth2RequestFactory and this in turn needs OAuth2 parameters to be specified in an instance of class OAuth2Parameters.
How can I reuse the credentials obtained using the Google Api in GData API?
I am already doing the thing you want to do,
Code for how I passed the GData tokens
Issue with OAuth2 authentication with google spreadsheet
i.e. I use a single OAuth2 access/refresh token set. Using the same tokens for both gdata calls & drive API calls.
This is the code that finally worked for me
public class AppFlowMetadata : FlowMetadata
{
private static readonly IAuthorizationCodeFlow flow =
new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = new ClientSecrets
{
ClientId = "randomstring.apps.googleusercontent.com",
ClientSecret = "shhhhhh!"
},
Scopes = new[] { DriveService.Scope.Drive, "https://spreadsheets.google.com/feeds", "https://docs.google.com/feeds", "https://www.googleapis.com/auth/userinfo.email", "https://www.googleapis.com/auth/userinfo.profile" },
DataStore = new FileDataStore("Drive.Api.Auth.Store")
});
public override string GetUserId(Controller controller)
{
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; } }
}
And then, in the controller, OAuth2 parameters were copied to GData
var result = await new AuthorizationCodeMvcApp(this, new AppFlowMetadata()).
AuthorizeAsync(cancellationToken);
OAuth2Parameters parameters = new OAuth2Parameters();
parameters.ClientId = "somestring.apps.googleusercontent.com";
parameters.ClientSecret = "shhhhhh!";
parameters.Scope = result.Credential.Token.Scope;
parameters.AccessToken = result.Credential.Token.AccessToken;
parameters.RefreshToken = result.Credential.Token.RefreshToken;
GOAuth2RequestFactory requestFactory = new GOAuth2RequestFactory(null, "MySpreadsheetIntegration-v1", parameters);
SpreadsheetsService service = new SpreadsheetsService("MySpreadsheetIntegration-v1");
service.RequestFactory = requestFactory;

Cannot get any facebook permissions with C# facebook SDK

I have a fairly simple site which allow users to connect via facebook.
I am using C# facebook sdk MVC.
At first i didn't need any specific permission so there were no problems for users to connect. my code looked like this
public class FacebookController : BaseController
{
public FacebookSession FacebookSession
{
get { return (new CanvasAuthorizer().Session); }
}
public ActionResult Profile()
{
var client = new FacebookClient(this.FacebookSession.AccessToken);
dynamic me = client.Get("me");
ViewBag.Name = me.name;
ViewBag.Id = me.id;
return View();
}
}
and on my webconfig
<facebookSettings appId="XXXXXXXXXXXXXX" appSecret="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"/>
After a while I needed more specific permissions so I added CanvasAuthorize to my action - as so
[CanvasAuthorize(Permissions = "user_about_me,user_relationships,email,publish_stream")]
public ActionResult Profile()
That got me this exception:
Exception Details: System.Exception: CanvasUrl is null or empty
So I added to my Webconfig the canvasUrl which got me the same error with out the canvasPage So now my web config has all 4
<facebookSettings appId="XXXXXXXXXX" appSecret="XXXXXXXXXXXXXXXXXXXXx" canvasUrl = "http://localhost:60606/" canvasPage = "https://apps.facebook.com/XXXXXXXXXXXX/"/>
So now my user can log in via facebook, my problem is that when he does log in he is getting redirect to my Facebook app (http://apps.facebook.com/XXXXXXXXX/facebook/profile)
instead back to my site(http://localhost:60606/facebook/profile)
How can I get the Permissions that i need and redirect my user back to my site after he logs in?
Thanks
Well, My bad
CanvasAuthorize is just as it sounds, authorization for canvas.
So you cannot use it without an app canvas on facebook.
What I should have done is use the FacebookOAuthClient
var oAuthClient = new FacebookOAuthClient(FacebookApplication.Current);
oAuthClient.RedirectUri = new Uri("XXXXXXXXXXXXXX");
var loginUri = oAuthClient.GetLoginUrl(new Dictionary<string, object> { { "state", null }, { "scope", "user_about_me,user_relationships,email" } });
return Redirect(loginUri.AbsoluteUri);

Resources