In our application, we need to send notifications to users by email for various event triggers.
I'm able to send email if I send as "Me" the current user, but trying to send as another user account returns an error message and I'd prefer it if notifications didn't come users' themselves and may contain info we don't want floating around in Sent folders.
What works:
await graphClient.Me.SendMail(email, SaveToSentItems: false).Request().PostAsync();
What doesn't work:
string FromUserEmail = "notifications#contoso.com";
await graphClient.Users[FromUserEmail].SendMail(email, SaveToSentItems: false).Request().PostAsync();
Also tried using the user object id directly:
await graphClient.Users["cd8cc59c-0815-46ed-aa45-4d46c8a89d72"].SendMail(email, SaveToSentItems: false).Request().PostAsync();
My application has permissions for the Graph API to "Send mail as any user" enabled and granted by the owner/administrator.
The error message returned by the API:
Code: ErrorFolderNotFound Message: The specified folder could not be
found in the store.
I thought this error might have been because the notifications account didn't have a sent folder, so I set the SaveToSentItems value to false, but I still get the same error.
Are there any settings I need to check on the account itself to allow the app to send mail on this account or should this work?
I have checked out the documentation here:
https://developer.microsoft.com/en-us/graph/docs/api-reference/v1.0/api/user_sendmail
Which appears to support what I'm trying to do, but doesn't reference any folder except for the sent items folder which I'm telling the API not to save to anyway.
We aren't intending to impersonate any actual user here, just send notification emails from within the app from this specific account (which I know is technically impersonation, but not of a real entity).
So like Schwarzie2478 we used a noreply#ourcompany.com address. But our AD is federated which means you can't use Username\Password auth and we didn't want to use the Application Mail.Send permission since it literally can send as anyone and there is no way IT Security would let that fly. So we used Windows Authentication instead.
This requires that you grant consent to the app to use the mail.send and user.read delegate permissions by going to https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/authorize?client_id={clientId}&response_type=code&scope=user.read%20mail.send and logging in with the windows user that the app will run as.
More info on using windows auth here: https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/Integrated-Windows-Authentication
// method call
var t = SendEmailUsingGraphAPI();
t.Wait();
// method
static async Task<Boolean> SendEmailUsingGraphAPI() {
// AUTHENTICATION
var tenantID = "YOUR_TENANT_ID"; //azure ad tenant/directory id
var clientID = "YOUR_APPS_CLIENT_ID"; // registered app clientID
var scopes = "user.read mail.send"; // DELEGATE permissions that the request will need
string authority = $"https://login.microsoftonline.com/{tenantID}";
string[] scopesArr = new string[] { scopes };
try {
IPublicClientApplication app = PublicClientApplicationBuilder
.Create(clientID)
.WithAuthority(authority)
.Build();
var accounts = await app.GetAccountsAsync();
AuthenticationResult result = null;
if (accounts.Any()) {
result = await app.AcquireTokenSilent(scopesArr, accounts.FirstOrDefault())
.ExecuteAsync();
}
else {
// you could acquire a token by username/password authentication if you aren't federated.
result = await app.AcquireTokenByIntegratedWindowsAuth(scopesArr)
//.WithUsername(fromAddress)
.ExecuteAsync(CancellationToken.None);
}
Console.WriteLine(result.Account.Username);
// SEND EMAIL
var toAddress = "EMAIL_OF_RECIPIENT";
var message = "{'message': {'subject': 'Hello from Microsoft Graph API', 'body': {'contentType': 'Text', 'content': 'Hello, World!'}, 'toRecipients': [{'emailAddress': {'address': '" + result.Account.Username + "'} } ]}}";
var restClient = new RestClient("https://graph.microsoft.com/v1.0/users/" + result.Account.Username + "/sendMail");
var request = new RestRequest(Method.POST);
request.AddHeader("Content-Type", "application/json");
request.AddHeader("Authorization", "Bearer " + result.AccessToken);
request.AddParameter("", message, ParameterType.RequestBody);
IRestResponse response = restClient.Execute(request);
Console.WriteLine(response.Content);
}
catch (Exception e) {
Console.WriteLine(e.Message);
throw e;
}
return true;
}
Whenever you are using delegated permissions (i.e. when a user is logged in), even though your admin has consented to the Mail.Send.Shared, it does NOT grant access to all mailboxes in the tenant. These OAuth permissions do not override the permissions (and restrictions) in place for the user.
If the user is not already configured with permissions to be able to "Send As" the notifications#contoso.com user, then you'll see this error.
To make it work, you'd need to actually grant "Send As" rights to all users that will be using your application.
This is a subtle thing, and granted it's a bit confusing. In the Azure portal, the permissions have slightly different descriptions, depending on if you're looking at the Application Permissions or the Delegated Permissions.
Application: Send mail as any user
Delegated: Send mail on behalf of others
Since you're using delegated, the permission doesn't allow you to send as any user, only send on behalf of any folks that the logged on user has rights to send as.
Another approach you could use here to avoid having to grant these rights to all users (which would allow them to send via Outlook, etc.) would be to have your backend app use the client credentials flow to get an app-only token. In that case, the app itself would have the permission to send as any user.
I don't know what others will have done for this, but I contacted Microsoft about this exact scenario: I want to send a mail as a fixed user ( noreply#mycompany.com) which has a mailbox in Azure. I want to send this mail from different applications or services.
The person there told me that sending a mail with no user logging in, is only possible with an delegated user token.
So we configured our application as an Native application in Azure like for mobile apps. Logging in for this application with the technical user during a setup phase gives me a delegated user token for that specific user which can be stored in a mailing service or component. This token does not expire ( at least not until the security changes of the user like password or something) and can be used to call the graph api to send mails when you give permission for this account to be sending mails from.
Next to that we even associated other shared mailboxes to this accounts to be able to send mails for those mailboxes too.
Documentation:
First You need a native app registration in Azure ( not an Web API):
https://learn.microsoft.com/en-us/azure/active-directory/develop/native-app
This app only requires an one-time login and approval from an user to get a token which can represent that user indefinitly. We set up a mail user account to be used for this. That token is then used to get access token to Graph Api for sending mails and such
Token Handling example:
https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/token-cache-serialization
With an identitytoken stored ( usually a .cache file somewhere) you can request an accesstoken:
Identity Client:
https://learn.microsoft.com/en-us/dotnet/api/microsoft.identity.client.publicclientapplication?view=azure-dotnet
_clientApp = new PublicClientApplication(ClientId, "https://login.microsoftonline.com/{xxx-xxx-xx}, usertoken,...
authResult = await _clientApp.AcquireTokenSilentAsync(scopes,...
private static string graphAPIEndpoint = "https://graph.microsoft.com/v1.0/me";
//Set the scope for API call to user.read
private static string[] scopes = new string[] { "user.read", "mail.send" };
private const string GraphApi = "https://graph.microsoft.com/";
var graphclient = new GraphServiceClient($"{GraphApi}/beta",
new DelegateAuthenticationProvider(
(requestMessage) =>
{
// inject bearer token for auth
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", authResult.AccessToken);
return Task.FromResult(0);
}));
var sendmail = graphclient.Users[User].SendMail(mail), true);
try
{
await sendmail.Request().PostAsync();
}
catch (Exception e)
{
Related
I am trying to do the following:
Establish a Cognito User Pool to manage sign-in/up/etc...
Assign individual roles to users
Obtain AWS credentials for the user which assume the roles defined for that particular user
To add more background: the goal using AWS/Cognito/Policies encompasses following aims (at user level):
Prevent misusage of AWS resources without valid entitlement
Offload the fine Grained control on what can be done with the costly AWS resources from the App to AWS (TTS, TTS Neural Voices, Quotas, ...)
Offer options for further App functionalities based on AWS Services but limit the risk of them being used freely with an hacked App and access keys
Eventually billing on usage
Clearly I haven't found the canonical way/place for these tasks, allthough AWS policies on a user level seem to be the right place. Because leaked credentials of a user could be blocked not impacting the rest of the pool.
For 1. this is done.
Currently I can Sign-in/-ou with the Userpool:
AmazonCognitoIdentityProviderClient provider = new AmazonCognitoIdentityProviderClient(new Amazon.Runtime.AnonymousAWSCredentials());
CognitoUserPool userPool = new CognitoUserPool("eu-central-1_XXXXXXXX", "xxxxxxxxxxxxxxxxxxxxxxxxx", provider);
CognitoUser user = new CognitoUser("Username", "yyyyyyyyyyyyyyyyyyyyyyyyy", userPool, provider);
//
// Authenticate User to AWS Cognito User Pool
//
InitiateSrpAuthRequest authRequest = new InitiateSrpAuthRequest()
{
Password = "PWD"
};
AuthFlowResponse authResponse = await user.StartWithSrpAuthAsync(authRequest).ConfigureAwait(false);
// Print Token
MessageBox.Show($"Token is : {authResponse.AuthenticationResult.AccessToken}");
For 2. I can have roles assigned to groups and the users of the user pool assigned to the groups.
For 3. This is where I am heading nowhere:
I can get temporary AWS credantials from the connected user as follows:
//
// Get Temporary Credentials for User
//
CognitoAWSCredentials awsCredentials = user.GetCognitoAWSCredentials("eu-central-1:zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz", RegionEndpoint.EUCentral1);
ImmutableCredentials iCredentials = awsCredentials.GetCredentials();
However. the credentials the user now has, are the credentials that are set to the Identity Pool, the usergroup is linked to for authenticated users. So any user connecting to that pool will have the same roles with these AWS credentials.
I cannot find any decent documentation or example showing what are the steps so to assign to each user individual roles, nor how to implement and control how users can assume other roles. Hence leave the identity pool without any privileges and let the users once connected retrieve the proper rights.
The groups assigned to the user in cognito user pool seem to have no effect on the roles attributed to the AWS credentials.
Also, for a service like AWS Polly, I could not find a way to use the Access Token of the user, returned during sign-in, which should contain the roles according to the users groups membership.
To stay with Polly this is the test code to get the speech:
//
// Create a client for the authenticated user
//
IAmazonPolly client = new AmazonPollyClient(iCredentials.AccessKey, iCredentials.SecretKey, iCredentials.Token, RegionEndpoint.EUCentral1);
//
// Use Polly client to generate speech
//
SynthesizeSpeechRequest synthesizeSpeechRequest = new SynthesizeSpeechRequest()
{
Engine = voice.HasModeNeural() ? Engine.Neural : Engine.Standard, // Try to use Neural engine
OutputFormat = OutputFormat.Mp3,
VoiceId = new VoiceId(voice.GetName()),
Text = sText,
};
// Fetch Audio
try
{
SynthesizeSpeechResponse synthesizeSpeechResponse = await client.SynthesizeSpeechAsync(synthesizeSpeechRequest);
return synthesizeSpeechResponse;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
I am trying to manipulate microsoft planner tasks (end goal is to create a task in a certain Scope and bucket).
I am already failing at listing a Plan or the buckets for a plan. I want to make this connection from a background service (daemon) so no interactive user login should take place. (with interactive login credentials i can make it work, but that's not what i need/want).
So i Created a new App Registration in Azure with the Api Permissions:
Group.Read.All (Delegated)
Group.ReadWrite.All (Delegated)
Tasks.Read (Delegated)
Tasks.Read.Shared (Delegated)
Tasks.ReadWrite (Delegated)
Tasks.ReadWrite.Shared (Delegated)
User.Read (Delegated)
Group.ReadWrite.All (Application)
Tasks.ReadWrite.All (Application)
User.ManageIdentities.All (Application)
User.ReadWrite.All (Application)
I also checked the "Allow public client flows" setting on the App registration Authentication tab.
I started by adding the ones prescribed on the official microsoft doc website about this topic. And then started adding some because i was still receiving Access Denied messages. Thus reaching this list. It should be enough according to microsoft.
Then i have this code to authenticate with Microsoft graph, giving me a graphclient instance which is successfully initialized:
private GraphServiceClient initializeTeamsGraphConnection(string TenantId, string ApplicationId, string ClientSecret)
{
// The client credentials flow requires that you request the
// /.default scope, and preconfigure your permissions on the
// app registration in Azure. An administrator must grant consent
// to those permissions beforehand.
var scopes = new[] { ScopeGraph };
// Multi-tenant apps can use "common",
// single-tenant apps must use the tenant ID from the Azure portal
var tenantId = TenantId;
// Values from app registration
var clientId = ApplicationId;
var clientSecret = ClientSecret;
// using Azure.Identity;
var options = new TokenCredentialOptions
{
AuthorityHost = AzureAuthorityHosts.AzurePublicCloud
};
// https://docs.microsoft.com/dotnet/api/azure.identity.clientsecretcredential
var clientSecretCredential = new ClientSecretCredential(
tenantId, clientId, clientSecret, options);
var graphClient = new GraphServiceClient(clientSecretCredential, scopes);
return graphClient;
}
So authentication seems to be succesful, but when i then try to list a plan using the code below:
private void CreateTask(GraphServiceClient client)
{
var graphTask = client.Planner.Plans["Sdonp-JNB0aInPxDcxMowZgACZ59"]
.Request()
.GetAsync();
while (!graphTask.IsCompleted)
{
graphTask.Wait(10000);
}
var plans = graphTask.Result;
I get following error:
403 - Forbidden: Access is denied.
You do not have permission to view this directory or page using the credentials that you supplied.
Access Permissions should be well above what is needed to do this. Any idea on what I am doing wrong?
Again this code is working because when i change authentication to some sort of interactive login type, i get this plan info no problem
Planner API currently supports only delegated permissions that's the reason why it returns 403 for daemon (background service).
According to this announcement, support for application permissions is coming soon.
On this page https://learn.microsoft.com/en-us/graph/sdks/choose-authentication-providers?tabs=CS#IntegratedWindowsProvider it is said "The interactive flow is used by mobile applications (Xamarin and UWP) and desktops applications to call Microsoft Graph in the name of a user."
So I developed a C# console app to login and query some data:
var clientId = "<APP GUID GOES HERE>";
var tenantId = "<APP TENANT GUID GOES HERE>";
var scopes = new[] {"user.read","Calendars.Read"};
var clientApplication = PublicClientApplicationBuilder
.Create(clientId)
.Build();
var authProvider = new InteractiveAuthenticationProvider(clientApplication, scopes);
var graphClient = new GraphServiceClient(authProvider);
User me = graphClient.Me.Request()
.GetAsync()
.Result;
During running the console app a login "page" comes out, I entered my credentials, but at the end the pagse says error "AADSTS500113: No reply address is registered for the application.", and the code got "user cancelled the login"
BTW: I dont want to login manually each time, I added my password to the code:
var scopes = new[] {"offline_access","user.read","Calendars.Read"};
var clientApplication = PublicClientApplicationBuilder
.Create(clientId)
.Build();
var authProvider = new UsernamePasswordProvider(clientApplication, scopes);
var graphClient = new GraphServiceClient(authProvider);
var pwd = ConvertToSecureString("<MYPASSWORD GOES HERE>");
User me = graphClient.Me.Request()
.WithUsernamePassword("<MY EMAIL GOES HERE>", pwd)
.GetAsync()
.Result;
In this case no login page shows up (good), but an exception raises: "The grant type is not supported over the /common or /consumers endpoints. Please use the /organizations or tenant-specific endpoint."
Then I added a WithTenantId(...) to the Build(), now I got different exception: "MsalUiRequiredException: AADSTS50076: Due to a configuration change made by your administrator, or because you moved to a new location, you must use multi-factor authentication to access '00000003-0000-0000-c000-000000000000'." but the multi-factor auth request does not come to my phone.
What goes wrong? What should I do to get this app work?
What I want is to execute this c# console app regularly on my desktop computer, without any interactions (logins) as my user to query some data using graph api. How to do that correctly?
Thanks in advance!
This error AADSTS500113: No reply address is registered for the application indicates that the reply URL is not available and AAD does not know where to send the token. To fix this, you need to add a valid redirect URI in your app registration in AAD.
The next error : MsalUiRequiredException in your case happens because the user needs to perform multiple factor authentication based your Azure AD policies. To do this, you need to change your flow from the current username/password provider to interactive authentication provider since in the former case, users who need to do MFA won't be able to sign-in (as there is no interaction).
This would look something like this:
IPublicClientApplication publicClientApplication = PublicClientApplicationBuilder
.Create(clientId)
.Build();
InteractiveAuthenticationProvider authenticationProvider = new InteractiveAuthenticationProvider(publicClientApplication, scopes);
You can then acquire the token interactively :
string[] scopes = new string[] {"user.read"};
var app = PublicClientApplicationBuilder.Create(clientId).Build();
var accounts = await app.GetAccountsAsync();
AuthenticationResult result;
try
{
result = await app.AcquireTokenSilent(scopes, accounts.FirstOrDefault())
.ExecuteAsync();
}
catch(MsalUiRequiredException)
{
result = await app.AcquireTokenInteractive(scopes)
.ExecuteAsync();
}
To authenticate without the user, your app can implement client credentials acquisition methods - these suppose that the app has previously registered a secret (application password or certificate) with Azure AD, which it then shares with this call. Please note that no user interactions means you can't use delegated permissions.
Let me know if this helps and if you have further questions.
My web service is currently doing basic username/password authentication in order to subscribe the exchange user for receiving the events (like new mail event etc) like below:
var service = new ExchangeService(exchangeVersion)
{
KeepAlive = true,
Url = new Uri("some autodiscovery url"),
Credentials = new NetworkCredential(username, password)
};
var subscription = service.SubscribeToPushNotifications(
new[] { inboxFolderFoldeID },
new Uri("some post back url"),
15,
null,
EventType.NewMail,
EventType.Created,
EventType.Deleted,
EventType.Modified,
EventType.Moved,
EventType.Copied);
Now, I am supposed to replace the authentication mechanism to use OAuth protocol. I saw some examples but all of them seem to be talking about authenticating the client (https://msdn.microsoft.com/en-us/library/office/dn903761%28v=exchg.150%29.aspx?f=255&MSPPError=-2147217396) but nowhere I was able to find an example of how to authenticate an exchange user with OAuth protocol. Any code sample will help a lot. Thanks.
It's not clear what you mean with 'web service' and how you currently get the username and password. If that is some kind of website where the user needs to login or pass credentials, then you'll have to start an OAuth2 grant from the browser as in redirecting the clients browser to the authorize endpoint to start implicit grant or code grant. The user will be presented a login screen on the OAuth2 server (and not in your application), once the user logs in a code or access token (depending on the grant) will be returned to your application which you can use in the ExchangeService constructor.
If that 'web' service is some service that runs on the users computer you can use one of the methods described below.
Get AccessToken using AuthenticationContext
The example seems to be based on an older version of the AuthenticationContext class.
The other version seems to be newer, also the AcquireToken is now renamed to AcquireTokenAsync / AcquireTokenSilentAsync.
No matter which version you're using, you will not be able to pass username and password like you're doing in your current code. However, you can let the AcquireToken[Async] method prompt for credentials to the user. Which, let's be honest, is more secure then letting your application deal with those user secrets directly. Before you know, you'll be storing plain text passwords in a database (hope you aren't already).
In both versions, those methods have a lot of overloads all with different parameters and slightly different functionality. For your use-case I think these are interesting:
New: AcquireTokenAsync(string, string, Uri, IPlatformParameters) where IPlatformParameters could be new PlatformParameters(PromptBehavior.Auto)
Old: AcquireToken(string, string, Uri, PromptBehavior where prompt behavior could be PromptBehavior.Auto
Prompt behavior auto, in both vesions, means: the user will be asked for credentials when they're not already cached. Both AuthenticationContext constructors allow you to pass a token-cache which is something you can implement yourself f.e. to cache tokens in memory, file or database (see this article for an example file cache implementation).
Get AccessToken manually
If you really want to pass in the user credentials from code without prompting the user, there is always a way around. In this case you'll have to implement the Resource Owner Password Credentials grant as outlined in OAuth2 specificatioin / RFC6749.
Coincidence or not, I have an open-source library called oauth2-client-handler that implements this for use with HttpClient, but anyway, if you want to go this route you can dig into that code, especially starting from this method.
Use Access Token
Once you have an access token, you can proceed with the samples on this MSDN page, f.e.:
var service = new ExchangeService(exchangeVersion)
{
KeepAlive = true,
Url = new Uri("some autodiscovery url"),
Credentials = new OAuthCredentials(authenticationResult.AccessToken))
};
In case someone is still struggling to get it to work. We need to upload a certificate manifest on azure portal for the application and then use the same certificate to authenticate the client for getting the access token. For more details please see: https://blogs.msdn.microsoft.com/exchangedev/2015/01/21/building-daemon-or-service-apps-with-office-365-mail-calendar-and-contacts-apis-oauth2-client-credential-flow/
Using the example code in this Microsoft Document as the starting point and these libraries:
Microsoft Identity Client 4.27
EWS Managed API v2.2
I am able to successfully authenticate and connect with Exchange on Office 365.
public void Connect_OAuth()
{
var cca = ConfidentialClientApplicationBuilder
.Create ( ConfigurationManager.AppSettings[ "appId" ] )
.WithClientSecret( ConfigurationManager.AppSettings[ "clientSecret" ] )
.WithTenantId ( ConfigurationManager.AppSettings[ "tenantId" ] )
.Build();
var ewsScopes = new string[] { "https://outlook.office365.com/.default" };
AuthenticationResult authResult = null;
try
{
authResult = cca.AcquireTokenForClient( ewsScopes ).ExecuteAsync().Result;
}
catch( Exception ex )
{
Console.WriteLine( "Error: " + ex );
}
try
{
var ewsClient = new ExchangeService();
ewsClient.Url = new Uri( "https://outlook.office365.com/EWS/Exchange.asmx" );
ewsClient.Credentials = new OAuthCredentials( authResult.AccessToken );
ewsClient.ImpersonatedUserId = new ImpersonatedUserId( ConnectingIdType.SmtpAddress, "ccc#pppsystems.co.uk" );
ewsClient.HttpHeaders.Add( "X-AnchorMailbox", "ccc#pppsystems.co.uk" );
var folders = ewsClient.FindFolders( WellKnownFolderName.MsgFolderRoot, new FolderView( 10 ) );
foreach( var folder in folders )
{
Console.WriteLine( "" + folder.DisplayName );
}
}
catch( Exception ex )
{
Console.WriteLine( "Error: " + ex );
}
}
The Microsoft example code did not work - the async call to AcquireTokenForClient never returned.
By calling AcquireTokenForClient in a separate try catch block catching a general Exception, removing the await and using .Result, this now works - nothing else was changed.
I realise that this is not best practice but, both with and without the debugger, the async call in the original code never returned.
In the Azure set-up:
A client secret text string was used - a x509 certificate was not necessary
The configuration was 'app-only authentication'
Hope this helps someone avoid hours of frustration.
I am trying to download a user's mailbox using the Email Audit API. I am getting a 403 Forbidden response to this code (the error occurs on the last line, the call to the UploadPublicKey method):
var certificate = new X509Certificate2(System.Web.HttpRuntime.AppDomainAppPath + "key.p12", "notasecret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] { "https://apps-apis.google.com/a/feeds/compliance/audit/" }
}.FromCertificate(certificate));
credential.RequestAccessTokenAsync(System.Threading.CancellationToken.None).Wait();
DebugLabel.Text = credential.Token.AccessToken;
var requestFactory = new GDataRequestFactory("My App User Agent");
requestFactory.CustomHeaders.Add(string.Format("Authorization: Bearer {0}", credential.Token.AccessToken));
AuditService aserv = new AuditService(strOurDomain, "GoogleMailAudit");
aserv.RequestFactory = requestFactory;
aserv.UploadPublicKey(strPublicKey);
I have created the service account in the Developers Console and granted the Client ID access to https://apps-apis.google.com/a/feeds/compliance/audit/ in the Admin console.
Seems to me like the account should have all the permissions it needs, yet it doesn't. Any idea what I am missing?
OK, so I gave up on trying to make it work with a service account even though that is what Google's documentation would lead you to believe is the correct way to do it. After emailing Google support, I learned I could just use OAuth2 for the super user account that created the application on the developer's console.
So then I worked on getting an access token for offline access (a refresh token) by following the process outlined here:
Youtube API single-user scenario with OAuth (uploading videos)
and then taking that refresh token and using it with this code:
public static GOAuth2RequestFactory RefreshAuthenticate(){
OAuth2Parameters parameters = new OAuth2Parameters(){
RefreshToken = "<YourRefreshToken>",
AccessToken = "<AnyOfYourPreviousAccessTokens>",
ClientId = "<YourClientID>",
ClientSecret = "<YourClientSecret>",
Scope = "https://apps-apis.google.com/a/feeds/compliance/audit/",
AccessType = "offline",
TokenType = "refresh"
};
OAuthUtil.RefreshAccessToken(parameters);
return new GOAuth2RequestFactory(null, "<YourApplicationName>", parameters);
}
which is code from here https://stackoverflow.com/a/23528629/5215904 (Except I changed the second to last line... for whatever reason the code shared did not work until I made that change).
So there I was finally able to get myself an access token that would allow me access to the Email Audit API. From there everything was a breeze once I stopped trying to mess around with a service account.