google service account authentication with json file in .net 4.0 - c#

Need to authenticate google service account with OAuth.
I have google credentials file in json format.
refereed Google Service Account Authentication with Json file
able to create RASParameters but didn't know how to proceed further.
I am very new to google apis implementation.
found various examples of .p12 file but didn't find one with .json file.
And i am using .net 4.0 framework so can't use the googlecredential class which is available from .net 4.5+ framework.

I think that what you need to create is a JsonCredentialParameters with that Json file you have. This class is under the Google.Apis.Auth.OAuth2 namespace, so you just need to have the proper Google Apis Auth package to do this.
Then you can create a new ServiceAccountCredential with the proper user account and scopes.
protected override ServiceAccountCredential GetCredential()
{
var credentialParameters = GetCredentialParameters();
return new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(credentialParameters.ClientEmail)
{
Scopes = Scopes,
User = User
}.FromPrivateKey(credentialParameters.PrivateKey));
}
JsonCredentialParameters GetCredentialParameters()
{
return JsonSerializer.Deserialize<JsonCredentialParameters>(new FileStream(File, FileMode.Open));
}

Related

Microsoft Graph Api - upload file and invalidRequest

I have a problem uploading files to sharepoint using the graph api.
With the token downloaded from https://developer.microsoft.com/en-us/graph/graph-explorer everything works fine. I get a response with a status of 200.
However, when I want to upload a file with a token received from AD I get an invalid request.
In the scope of my token there is: "Files.ReadWrite Files.ReadWrite.All Group.Read.All Group.ReadWrite.All GroupMember.Read.All GroupMember.ReadWrite.All openid profile Sites.Read.All Sites.ReadWrite.All User.Read email".
Reading the file list works without any problems
Below is the code on how I generate the token to Graph Api
Firstly, pls don't show your code in your picture because we can't copy code from picture directly so that we can't test your code and reproduce your issue.
In your screenshot, I can see you used https://graph.microsoft.com/.default as the scope, and since you used a console application, so you should use client credential flow to generate the author provider so that you can generate a correct access token. And this can also explain why you used the token obtained from graph explorer can work. When we use graph explorer, it will ask us to sign in first so that it can generate an access token which containing delegate api permission. And in your code you used var authProvider = new DelegateAuthenticationProvider.
You also shared the api permissions, but when you used client credential flow, you have to set the application api permission but not the delegate api permission. For this upload file api, the permission should be Files.ReadWrite.All, Sites.ReadWrite.All. Pls don't forget the give the api permission.
By the way, since you've used the graph SDK, you can use my code snippet to call graph api.
using Microsoft.Graph;
using Azure.Identity;
var scopes = new[] { "https://graph.microsoft.com/.default" };
string tenantId = "TenantId";
string clientId = "ClientId";
string clientSecret = "ClientSecret";
var clientSecretCredential = new ClientSecretCredential(
tenantId, clientId, clientSecret);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
var uploadFile = await graphClient.Drives[drives].Root.xxxx;

Is there way to authenticate to Graph API using Username and Password without Application Registration in Azure AD

I'm creating an app that needs to authenticate to multiple Office 365 applications in differing tenants using the Graph API. If I follow Microsoft's guidance I can do this, but I have to register the app in each new Azure AD which adds quite a lot of overhead for the user. I'd like to be able to avoid this step and use a username and password only in the authentication provider. This is the link to the Microsoft page which gives example code: https://learn.microsoft.com/en-us/graph/sdks/choose-authentication-providers?tabs=CS#usernamepassword-provider
Thanks
Nathan
Is there way to authenticate to Graph API using Username and Password without Application Registration in Azure AD?
To access the data in Microsoft Graph, your application will need to
acquire an OAuth 2.0 access token. To achieve access token you must need
application Id.No way to bypass it.
Unfortunately, You have to register an App for accessing Microsoft Graph API resources. Because Graph API requires ApplicationId, Application Secret to authenticate request. In that case you have no other options. Its a application architecture.
As you may know, to use Graph API you need to use any of the authentication grant flow provided by Microsoft. If you seen the documentation you would know that each of the application at least need to have application Id which Graph API uses to trace the request is for.
For more details you can have a look official docs
You need your application registration to get the ClientID and TenantID and the permissions to use the Graph API, but you could use without the token with user and password.
With this (max) combination of Libraries (You could not use the 3 first):
Azure.Core 1.24.0
Azure.Identity 1.6.0
Microsoft.Bcl.AsyncInterfaces 6.0.0
Microsoft.Graph 3.35.0
Microsoft.Graph.Auth 1.0.0 Preview 7
Microsoft.Graph.Core 1.25.1
Microsoft.Identity.Client 4.39.0
Microsoft.Identity.Client.Extensions.Msal 2.19.3
Just because Microsoft.Graph.Auth is deprecated (No more updates)
using Microsoft.Graph;
using Microsoft.Graph.Auth;
using Microsoft.Identity.Client;
using System.Security;
In the function you are goint to work you could use:
GraphServiceClient graphClient = await CreateGraphClient();
To set your password (with or without the static):
public static SecureString Password
{
get
{
var password = "xxxxxxxxx";
if (password.StartsWith("Error."))
throw new InvalidProgramException(password);
SecureString secPass = new SecureString();
password.ToCharArray().ToList().ForEach(secPass.AppendChar);
secPass.MakeReadOnly();
return secPass;
}
}
internal static string UserName { get; } = "Usuario";
And you could define (with or without the static) the function as:
internal static async Task<GraphServiceClient> CreateGraphClient()
{
var pass = Password;
IPublicClientApplication publicClientApplication = PublicClientApplicationBuilder
.Create(ClientID)
.WithTenantId(TenantID)
.Build();
UsernamePasswordProvider authProvider = new UsernamePasswordProvider(publicClientApplication);
GraphServiceClient graphClient = new GraphServiceClient(authProvider);
try
{
User usr = await graphClient.Me.Request().WithUsernamePassword(UserName, pass).GetAsync();
}
catch {
throw;
}
return graphClient;
}

Authorized failed when run Google.Apis.YouTube.Samples.Upload project from Github

I am new from youtube api. I would like to have a console program schedule upload videos to youtube without authorization everytime.
I see many posts and videos but not the complete story, I download the sample from Github and try to run it. It failed.
i follow the guide that
。create OAuth client ID and application type choose Other
。download code from github
。click allow in browser, lets youtube api manage youtube account.
img1 - client secret download from console developer and code from github
img2 - error message told me unauthorized
which part is wrong, how can i fix it? Please help!
The error your getting means that you have not authenticated the YouTubeService there must be something wrong with your credentials which i cant see because you haven't posted all your code.
The YouTube API does not support service accounts. You will need to authenticate your code at least once. This is done via a web browser and the client library you are using will store the credentials for "user" in %appData% directory.
The tutorial you are following doesn't say anything about not needing authentication. This is the code for the auth.
UserCredential credential;
using (var stream = new FileStream("client_secrets.json", FileMode.Open, FileAccess.Read))
{
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.Load(stream).Secrets,
// This OAuth 2.0 access scope allows for full read/write access to the
// authenticated user's account.
new[] { YouTubeService.Scope.Youtube },
"user",
CancellationToken.None,
new FileDataStore(this.GetType().ToString())
);
}

Access sharepoint search rest api

I have a problem. I use Azure AD to authenticate my asp.net app. Authentication works fine. Then I from this app trying to access OneDrive for Business using sharepoint search rest api. But the server always receives a response with a 401 error. I understand that the problem is in the access token which I use (Now I use the token received from Azure AD). But I never found the normal description of how to obtain an access token for the sharepoint search rest api.
Thanks in advance
Answer
You need to give your ASP.NET Application permission to use your OneDrive for Business application.
Here is an overview of how to do this using the Azure Management Portal. (Note that your OneDrive for Business account is a type of Office 365 SharePoint Online account.)
Go to manage.windowsazure.com > Active Directory > Your Tenant. If your tenant has an associated OneDrive for Business account, then its list of applications will include Office 365 SharePoint Online.
If your tenant's list of application does include Office 365 SharePoint Online, then your next step is to give your ASP.NET Web Application permission to access it.
Open up your Web Application's page in the Azure Active Directory area. Then choose CONFIGURE > Add Application. Add the Office 365 SharePoint Online application. Give it all necessary permissions and save.
The following screenshot is for a Native Client Application, because that is what my demo code is using. You can do a similar thing for a Web Application, though you will need to use an X509 Certificate for authentication instead of a username/password.
Your access token will now work with your Office 365 for Business account. Hooray!
Demo
Here is some sample code that works on my machine with a Native Client App. You can do the same thing with a Web Application, though you will need to use an X509 Certificate instead of a username/password.
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System.Net;
namespace AAD_SharePointOnlineApp
{
class Program
{
static void Main(string[] args)
{
var authContext =
new AuthenticationContext(Constants.AUTHORITY);
var userCredential =
new UserCredential(Constants.USER_NAME, Constants.USER_PASSWORD);
var result = authContext
.AcquireTokenAsync(Constants.RESOURCE, Constants.CLIENT_ID_NATIVE, userCredential)
.Result;
var token = result.AccessToken;
var url = "https://mvp0.sharepoint.com/_api/search/query?querytext=%27timesheets%27";
var request = WebRequest.Create(url);
request.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + token);
var response = request.GetResponse() as HttpWebResponse;
}
}
class Constants
{
public const string AUTHORITY =
"https://login.microsoftonline.com/mvp0.onmicrosoft.com/";
public const string RESOURCE =
"https://mvp0.sharepoint.com";
public const string CLIENT_ID_NATIVE =
"xxxxx-xxxx-xxxxx-xxxx-xxxxx-xxxx";
public const string USER_NAME =
"MY_USER#mvp0.onmicrosoft.com";
public const string USER_PASSWORD =
"MY_PASSWORD";
}
}
Comments
If you are trying to do the above with a Web Application instead of a Native Client Application, then you will need to use an X509 Certificate, otherwise you will receive the following error.
Unsupported app only token.
See also: http://blogs.msdn.com/b/richard_dizeregas_blog/archive/2015/05/03/performing-app-only-operations-on-sharepoint-online-through-azure-ad.aspx

Using Google SpreadsheetsService with Service Account

I need to make some changes to existing Spreadsheet in Google Drive. I want to do that periodically, using scheduled process. Due to this I decided to use service account authentication, which is described here https://developers.google.com/drive/web/delegation
The example is working fine and I can connect to the Plus API, however I need to connect to Google Spreadsheet API. The problem is that SpreadsheetsService does not seems to work with p12 files or Initializer class as DriveService does.
SpreadSheetsService has only 2 authentication methods which seems not to require to go by provided url - SetAuthenticationToken() and setUserCredentials(). There is no obvious way I can pass p12 file to the SpreadsheetService.
Did anyone solved this problem? I am okay with any "dirty" solution like decrypting p12 file (thought I don't think google provides password for this) or putting authentication headers from DriveService to SpreadsheetService. Did anyone solved this problem?
Or maybe there are 3rd parties libraries for C# that supports Spreadsheet API login via Service account?
Thanks.
Please refer to How to use SpreadsheetsService authenticated by ServiceAccountCredential?
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(ServiceAccount) {
Scopes = new[] {DriveService.Scope.Drive,"https://spreadsheets.google.com/feeds"}
}.FromCertificate(certificate)
);
bool success = credential.RequestAccessTokenAsync(System.Threading.CancellationToken.None).Result;
....
SpreadsheetsService spreadsheetsService = new SpreadsheetsService(applicationName);
var requestFactory = new Google.GData.Client.GDataRequestFactory(applicationName);
requestFactory.CustomHeaders.Add(string.Format("Authorization: Bearer {0}", credential.Token.AccessToken));
spreadsheetsService.RequestFactory = requestFactory;

Categories