EWS from WebSite using user credentials and windows authentication for intranet - email

I am trying to understand how I should configure a web site (ASP.Net) that need to pass the user credential and get some mail things
I get different kind of errors depending on the app pool configure,
What is the complete way to do it? I mean code + Configuration ;o)
I don't want to write the user and password but get them through the windows authentication
Thanks
code:
Service = new ExchangeService(ExchangeVersion.Exchange2010_SP2)
{
Url =
new Uri(
"https://xxx/yyy.asmx"),
//UseDefaultCredentials = true doesnt help
};
var view = new ItemView(1820);
// Find the first email message in the Inbox that has attachments. This results
FindItemsResults<Item> results = Service.FindItems(folderName, view);
//Here I get the error 401

Take a look at Get started with EWS Managed API client applications, it covers the basics to get you up and rolling. Note that when you use UseDefaultCredentials, you have to be on a domain joined machine, with the user logged in, and you must be targeting an on-prem server. We tested that scenario out and the following code works in that scenario.
using System;
using Microsoft.Exchange.WebServices.Data;
namespace HelloWorld
{
class Program
{
static void Main()
{
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010_SP2);
service.UseDefaultCredentials = true;
service.TraceEnabled = true;
service.TraceFlags = TraceFlags.All;
//Replace the URL below with your own, but using AutoDiscover is recommended instead
service.Url = new Uri("https://computer.domain.contoso.com/EWS/Exchange.asmx");
FindItemsResults<Item> results = service.FindItems(WellKnownFolderName.Inbox,
new ItemView(1));
}
}
}
If that doesn't work for you, then you might want to try using impersonation. See this thread, where I think they've got a similar situation . More information about impersonation is on MSDN: Impersonation and EWS in Exchange.

Related

How to interact with html response from http request in Flutter

I have a Flutter app where I am running a Google Apps Script through an http request. The purpose of the script is to create a Form and link the responses to a spreadsheetID that is passed in. The script is configured to only allow Google accounts access it and I've set up the flutter app to use a Service Account to access the script using the format:
getCredentials().then( (AuthClient client){
response = client.get(url, headers{"Authorization": "Bearer ${client.access_token}");
});
Issue: The issue is that the first time that the Service Account makes a request it will get an HTML response saying that it the account needs to give permission to the script to access its data and I'm not sure how to do that.
I'm fairly new to making http requests and using it with the GoogleAPI so I'm stuck. Any advice?
Goal
Create a web page which anyone can use to submit a Google sheet link and for the app to create a form and link the sheet to that.
Authorization
For this users will require a google account and they will be required to go through the OAuth process to authorize your app.
To create the form and link it from client-side JavaScript you would indeed need to call the Apps Script API, though you cannot do this with a service account.
From: https://developers.google.com/apps-script/api/how-tos/execute
Warning: The Apps Script API doesn't work with service accounts.
Luckily, you don't need a service account to do this.
Instructions
Create an Apps Script project with a function something like:
function createForm(ssID){
form = FormApp.create("Your New Form");
form.setDestination(FormApp.DestinationType.SPREADSHEET, ssID);
let formLink = form.getPublishedUrl();
return formLink;
}
Save and take a note of the ID of the script project.
Set up a GCP project (sounds like you already have one).
Make sure the Apps Script API is enabled in your GCP.
Configure the OAuth consent screen and add the scope - https://www.googleapis.com/auth/forms.
Create an API key and a Client ID - add http://localhost:8000 or whatever port you are testing on to the "Authorized JavaScript Origins"
Create OAuth credentials "web browser (JavaScript)".
Link your Apps Script project to the same GCP project - Instructions
Deploy the Apps Script project as an API executable - take not of the deployment ID, although the documentation says that you need the script ID, it is wrong, at least with the new Apps Script IDE.
Write the client-side JavaScript in your app like what is found in the quickstart. Which will enable users to authorize the app. You need to add in the scopes and keys there too. I recommend just following the quick start steps first to get a feel for it. You can use the authorization parts without modification.
Then add in the function that will call your Apps Script, something like this:
function appsScriptCreateForm(ssId) {
var scriptId = "<DEPLOYMENT_ID>";
// Run your Apps Script function
gapi.client.script.scripts
.run({
scriptId: scriptId,
resource: {
function: "createForm",
parameters: [ssId],
},
})
.then(function (resp) {
var result = resp.result;
// ERROR HANDLING
if (result.error && result.error.status) {
appendPre("Error calling API:");
appendPre(JSON.stringify(result, null, 2));
} else if (result.error) {
var error = result.error.details[0];
appendPre("Script error message: " + error.errorMessage);
if (error.scriptStackTraceElements) {
appendPre("Script error stacktrace:");
for (var i = 0; i < error.scriptStackTraceElements.length; i++) {
var trace = error.scriptStackTraceElements[i];
appendPre("\t" + trace.function + ":" + trace.lineNumber);
}
}
// IF SUCCESSFUL
} else {
console.log("success", resp);
}
});
}
Write your HTML with the buttons and inputs necessary.
Add event listeners where appropriate.
Profit!
Please note
This set up is your project running with the authorization of other accounts.
The API requests count against your quota.
You can see details of all the executions in your GCP Project Dashboard.
Users require a Google account and need to authorize the app.
In the Apps Script function above, you just need to pass in the Spreadsheet ID. Not the whole link. You could ask for the whole link and then use Regex to extract the ID if you wanted.
This can be quite tricky and easy to miss a step or make a mistake, so double check your work.
If, after successful authorization, when trying to run the script you get a 404 error, the request has been built wrong, check your IDs. If you get a 500 error, that can mean that the Apps Script function has successfully been called, but, there was an error within Apps Script and failed, check the executions page of the Apps Script editor.
References
Apps Script How to Execute
Apps Script JS Quickstart - Highly recommended you follow these steps first and get that working!
How to link your Apps Script to GCP

Running Google Apps Script through https request with Service Account credentials

I'm working on a Flutter app. And I've been trying to run my web-app Google Apps Script through http request since I'm required to use a Service Account and that access isn't supported in the Apps Script API. But I keep getting a 403/Forbidden response to the requests. I have the credentials for the Service Account and I am using its access token in my request but it still doesn't work.
I'm a novice at http requests and new to Google's authentication protocols so I'd appreciate some insight.
Thanks in advance.
Code:
return await driveUtils.getCreds(context).then((creds) async {
final drive_scopes = [drive.DriveApi.DriveReadonlyScope, "https://www.googleapis.com/auth/drive.file"];
final script_scopes = [app_scripts.ScriptApi.ScriptDeploymentsScope];
return await clientViaServiceAccount(creds, script_scopes+drive_scopes).then((AuthClient client) async {
debugPrint("url = " + url);
debugPrint("token = " + client.credentials.accessToken.data);
return await client.get(url,
headers: {
"Authorization": "Bearer ${client.credentials.accessToken.data}"
}
);
}, onError: onClientError);
}, onError: onCredsError);
Background: The script creates a Form and sets it Destination to a Spreadsheet's ID. Hence, the app requires that anyone who runs it to have a Google account to become the owner of the new Form and obtain access to the Sheet.
Update: It seems that Service Accounts can only access scripts that are within the same Google Cloud Project. This is a big issue since the point of the script is to create a central place for acquiring Form creation functionality for my app. And the app is intended to be used by anyone.
Does anyone have any ideas? Assuming a Service Account is the right Google Credentials for my app, I essentially need the ability to:
Create a Form that can be assigned to a user
Designate a user's spreadsheet as the forms response location
Retrieve the forms publishedURL
#Tanaike helped me figure out the issue. In order to make the script visible and able to run with a Service Account I had to change the Share setting for viewing the script. Simple solution

How to impersonate an admin user when using getClient() in the Google API NodeJS client

Per the recommendation in the defaultauth sample, I am trying to access the directory api for a domain which I have created a service account for. Here is the code I am attempting to connect with:
import { google } from 'googleapis'
const authClient = await google.auth.getClient({
scopes: ['https://www.googleapis.com/auth/admin.directory.user.readonly']
})
const service = google.admin('directory_v1')
console.log(
await service.users.list({
auth: authClient,
domain: <redacted>
})
)
However, when I attempt to connect I recieve an error saying Error: Not Authorized to access this resource/api. If I remove the creds.json file in ~/.google, the error changes to saying that it cannot find the credentials file. Also, I am able to access a bucket using the same file, so I'm pretty sure my local environment is set up correctly, authentication wise. I have also worked for the past few days with someone on the support team G Suite API team, who assures me that things are set up correctly on my domain.
After looking around online, it seems the thing I am missing is impersonating an admin account when trying to connect with my service-account. I have found a few examples online of doing this with a JWT auth strategy, but I would like to continue to use the default auth client, in order to abstract away the implementation details. Is this possible? If so, what do I have to change? I have tried setting subject, and delegationEmail in both of the calls (getClient and list).
Any help would be greatly appreciated.
Just set subject of the client object:
authClient.subject = 'your email address'
Google's api documentations highly varies by language. No standart. Something documented in PHP client may be missing in nodejs client and it can take hours to find out how to do it.
You can pass clientOptions.subject in the constructor.
import { google } = from 'googleapis';
const authClient = new google.auth.GoogleAuth({
scopes: ['https://www.googleapis.com/auth/admin.directory.user.readonly'],
clientOptions: {
subject: "your email address"
});

ADFS single sign on for logged on user not working

I am trying to integrate our application a regular .net desktop service that runs in the user context with ADFS, and a Web API. The user is a domain user and this is a regular AD environment. The MVC aspect of the website are working well with the browser.
I am on ADAL3(VS2017), windows server 2016, I referred this link [ADFS SSO CloudIdentity] am able to use UserCredentialPassword to get a token successfully and call into my Web API, I just followed the steps and changed things to async.
However using the logged on credential bit where a new UserCredential() should indicate to call to get the token from current thread doesn't work at all for me, on ADAL 2, I am getting null pointer exception and on ADAL3 I get
MSIS7065: There are no registered protocol handlers on path /adfs/oauth2/token to process the incoming request.
I did see a similar query on SO but based on my understanding the OP there is falling back on browser based behaviour.
Falling back at browser based auth (with Promptbehaviour.never) based behaviour is undesired because I have seen a lot of config issues on customer site where even with the relevant settings enabled the browser was assuming it to be an internet site and logging in fails.
Code for reference
string authority = "https://adfs.domain.com/adfs";
string resourceURI = "https://local.ip:44325";
string clientID = "19cda707-b1bf-48a1-b4ac-a7df00e1a689";
AuthenticationContext ac = new AuthenticationContext(authority, false);
// I expect that the user's credential are picked up here.
AuthenticationResult authResult =
await ac.AcquireTokenAsync(resourceURI, clientID,
new UserCredential());
string authHeader = authResult.CreateAuthorizationHeader();
var client = new HttpClient();
var request = new HttpRequestMessage( HttpMethod.Get,
"https://local.ip:44325/api/values");
request.Headers.TryAddWithoutValidation( "Authorization", authHeader);
var response = await client.SendAsync(request);
string responseString = await response.Content.ReadAsStringAsync();
The call fails in acquiretokenasync.
Have you violated any of the constraints described here?
Also, similar question here around ADAL V3.0 and UserCredential support.
In the link above, the RP was created using PowerShell. Are you sure that you have properly configured an application in ADFS 4.0 - clientID etc.

agsXMPP OnAuthError on different id

hi i am connecting to facebook using the following code it work fine for my two account one is gmail and another one is yahoo but it is only working on that accounts not log in on the other accounts of the gmail,yahoo,hotmail i check every acccount that i have every time onautherror come why ? what i am doing wrong is my code is wrong can any one tell me plz
Jid jidUser = new Jid(txtBoxUserName.Text);
xmppCon.ConnectServer = jidUser.Server;
xmppCon.Username = jidUser.User;
xmppCon.Server = "chat.facebook.com";
xmppCon.Port = 5222;
xmppCon.Password = txtBoxPassword.Text;
xmppCon.AutoResolveConnectServer = true;
xmppCon.Open();
Facebook doesn't allow the username/password XMPP authentication anymore.
You can only login using the X_FACEBOOK_PLATFORM SASL mechanism.
See:
http://developers.facebook.com/blog/post/2011/09/09/platform-updates--operation-developer-love/
So for Facebook use X_FACEBOOK_PLATFORM SASL auth in agsXMPP and it will work fine.