Using EWS Managed Api with Office 365 Api - c#

I am trying to use EWS managed Api with Office 365 Api via Azure AD. I have done the following tasks so far.
I have the admin privilege in Azure AD.
I have successfully registered my application in Azure AD.
I got Client ID, App key and resource ID from Azure AD.
I have enabled "Have full access to user's mailbox. as suggested by Jason.
I have successfully created a MVC5 web application.
I have followed this blog post of Jeremy.
Here the link of the blog I have followed :
http://www.jeremythake.com/2014/08/using-the-exchange-online-ews-api-with-office-365-api-via-azure-ad/#comment-280653
Code in my controller:
var outlookClient = await AuthHelper.EnsureOutlookServicesClientCreatedAsync("Mail");
IPagedCollection<IMessage> messagesResults = await outlookClient.Me.Messages.ExecuteAsync();
string messageId = messagesResults.CurrentPage[0].Id;
string tokenx = AuthHelper.GetSessionToken();
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013);
service.HttpHeaders.Add("Authorization", "Bearer " + tokenx);
service.PreAuthenticate = true;
service.SendClientLatencies = true;
service.EnableScpLookup = false;
service.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
ExFolder rootfolder = ExFolder.Bind(service, WellKnownFolderName.MsgFolderRoot);
Edited : I am getting accessToken Successfully and using it to make call against EWS managed Api, but it fails with 403:Forbidden exception. Your help will be highly appreciated.
best regards,

Jason Johnston helped me solve my problem.
The link:
Office 365 / EWS Authentication using OAuth: The audience claim value is invalid
I checked the EWS trace, I learned that EWS was complaining about invalid token and insufficient privileges. I re-registered my application to Azure AD and enabled full access to mailbox.
I commented this below code.
//var outlookClient = await AuthHelper.EnsureOutlookServicesClientCreatedAsync("Mail");
//try
//{
// IPagedCollection<IMessage> messagesResults = await outlookClient.Me.Messages.ExecuteAsync();
// string messageId = messagesResults.CurrentPage[0].Id;
//}
//catch
//{
// System.Diagnostics.Debug.WriteLine("Something bad happened. !!");
//}
I am getting access token from this below link sample.
https://github.com/OfficeDev/Office-365-APIs-Starter-Project-for-ASPNETMVC
Here is the complete code of controller which does the main task of authentication.
string resourceUri = "https://outlook.office365.com";
var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
AuthenticationContext authContext = new AuthenticationContext(Settings.Authority, new NaiveSessionCache(signInUserId));
string tokenx = await AuthHelper.AcquireTokenAsync(authContext, resourceUri, Settings.ClientId, new UserIdentifier(userObjectId,UserIdentifierType.UniqueId));
System.Diagnostics.Debug.WriteLine("Token:" + tokenx);
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013);
service.TraceListener = new EwsTrace();
service.TraceEnabled = true;
service.TraceFlags = TraceFlags.All;
service.HttpHeaders.Add("Authorization", "Bearer " + tokenx);
service.PreAuthenticate = true;
service.SendClientLatencies = true;
service.EnableScpLookup = false;
service.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
ExFolder rootfolder = ExFolder.Bind(service, WellKnownFolderName.MsgFolderRoot);
Console.WriteLine("The " + rootfolder.DisplayName + " has " + rootfolder.ChildFolderCount + " child folders.");
The important thing I noticed is I can't use the same token to access office365 api and EWS managed Api as EWS works with full mailbox access while office365 doesn't. I request the developer to confirm this,maybe I am doing something wrong, however my problem is solved for now.

Yep, that's right. The scope required for EWS isn't compatible with the Office 365 APIs, and vice versa.

Related

Azure AD Authentication with Salesforce

We are getting an error while authenticating Azure AD with Salesforce
'The user or administrator has not consented to use the application
with ID '1d75cc30-c553-4733-9a88-501e1b45821a' named 'Salesforce'.
Send an interactive authorization request for this user and resource'
.
We have Created an app in Azure directory and also granted all the required permissions to the app.
We are using HTTP request to get the authentication token.
List<String> urlParams = new List<String> {
'grant_type=authorization_code',
'code=' + EncodingUtil.urlEncode(code, 'UTF-8'),
'client_id=' + EncodingUtil.urlEncode(client_id, 'UTF-8'),
'client_secret=' + EncodingUtil.urlEncode(client_secret, 'UTF-8'),
'redirect_uri=' + EncodingUtil.urlEncode(redirect_uri, 'UTF-8'),
'resource=' + EncodingUtil.urlEncode('https://outlook.office365.com', 'UTF-8')
};
String body = String.join(urlParams, '&');
Http h = new Http();
HttpRequest req = new HttpRequest();
req.setEndpoint(access_token_url);
req.setMethod('POST');
//req.setHeader('Content-Type', 'application/json');
req.setHeader('Content-Type', 'application/x-www-form-urlencoded');
req.setHeader('Accept', 'application/json');
req.setBody(body);
HttpResponse res = h.send(req);
Please suggest what could be wrong here.

Make API call with Basic Auth using App Pool Credentials

I am wondering if in .NET, if it possible to send over the credentials of the identity running an application pool in IIS to an API that uses Basic Auth. I have successfully been able to retrieve the identity context from the application pool. However, in every example i see for using Basic Auth. They all seem to require to manually add the Authorization header to the request. This is a problem since i do not directly have access to the password of the windows identity thus i can't manually create the Basic Auth Token. I have been trying to use the .DefaultCredentials property but it fails to generate the Auth header thus the response fails with 401. If this isn't possible then i'll take a different approach but wanted to make sure before i do so. The full code sample is below...i have tried multiple ways but all end up with the same 401.
using (var impersonationContext = WindowsIdentity.Impersonate(IntPtr.Zero))
{
HttpWebRequest request1 = (HttpWebRequest)WebRequest.Create("url");
HttpClient request2 = new HttpClient();
WebClient request3 = new WebClient();
WebRequest request4 = WebRequest.Create("url");
try
{
// this code is now using the application pool indentity
try
{
//Method 1
//request1.UseDefaultCredentials = true;
//request1.PreAuthenticate = true;
//string encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(WindowsIdentity.GetCurrent().Name + ":" + "No password :("));
//request1.Headers.Add("Authorization", "Basic " + WindowsIdentity.GetCurrent().Token.ToString());
//HttpWebResponse response = (HttpWebResponse)request1.GetResponse();
//using (var reader = new StreamReader(response.GetResponseStream()))
//{
// JavaScriptSerializer js = new JavaScriptSerializer();
// var objText = reader.ReadToEnd();
// Debug.WriteLine(objText.ToString());
//}
////Method 2
//client.DefaultRequestHeaders.Accept.Clear();
//client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", WindowsIdentity.GetCurrent().Token.ToString());
//HttpResponseMessage response2 = client.GetAsync("url").Result; //.Result forces sync instead of async.
//var result = response2.Content.ReadAsStringAsync().Result;
//Debug.WriteLine(result);
//Method 3
//client2.Credentials = CredentialCache.DefaultNetworkCredentials;
//var result2 = client2.DownloadString("url");
//Debug.WriteLine(result2);
//Method 4
//request4.Credentials = CredentialCache.DefaultCredentials;
//string result4;
//using (var sr = new StreamReader(request4.GetResponse().GetResponseStream()))
//{
// result4 = sr.ReadToEnd();
//}
//Debug.WriteLine(result4);
}
catch (Exception ex)
{
throw new Exception("API Call Failed: " + ex.ToString() + " for " + WindowsIdentity.GetCurrent().Name + " request: " + request4.Headers.ToString());
}
}
finally
{
if (impersonationContext != null)
{
impersonationContext.Undo();
}
}
App Pool Identity and Basic Auth serves two different purpose and I suggest not to mix those. As you also mentioned that you don't know the password of app pool identity and it's self explanatory. App pool identity also allows the API's to access system resources for example, accessing a file share.
Whereas Basic Auth allows you to secure your API as a whole from being wide open and anyone accessing it. Except the ones who knows UserName:Password which needs to be passed with each HttpRequest (containing HttpHeader with UserName:Password in Base64).
Considering these facts, when API developer needs to share UserName and Password with all the parties, it's advisable not to share App Pool Identity credentials.
I have worked with both App Pool Identity and Basic Auth and I recommend to keep these separate.

EWS: "The remote server returned error (401) Unauthorized"

I'm trying to find a single item fronm all items in the current context, but I seem to constantly get this error message:
The request failed. The remote server returned an error: (401) Unauthorized.
First, I set everything up to access the exchange service:
var signInUserId = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
var userObjectId = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
AuthenticationResult authenticationResult = null;
AuthenticationContext authenticationContext = new AuthenticationContext(
SettingsHelper.Authority, new model.ADALTokenCache(signInUserId));
authenticationResult = authenticationContext.AcquireToken(
SettingsHelper.ServerName,
new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret));
ExchangeService exchange = new ExchangeService(ExchangeVersion.Exchange2013);
exchange.Url = new Uri(SettingsHelper.ServerName + "ews/exchange.asmx");
exchange.TraceEnabled = true;
exchange.TraceFlags = TraceFlags.All;
exchange.Credentials = new OAuthCredentials(authenticationResult.AccessToken);
And then I define what Item I want to receive (by ID):
ItemView view = new ItemView(5);
view.PropertySet = new PropertySet(BasePropertySet.IdOnly);
var tempId = id.Replace('-', '/').Replace('_', '+');
SearchFilter.IsEqualTo searchid = new SearchFilter.IsEqualTo(ItemSchema.Id, tempId);
And last but not least, I try to search for this item, within my items:
FindItemsResults<Microsoft.Exchange.WebServices.Data.Item> results = exchange.FindItems(WellKnownFolderName.Inbox, searchid, view);
And this is where my error happens. I've tried various other ways of doing this, but no matter what I do, I get unauthorized.
Could someone maybe guide me in the correct way, in order to solve this issue?
EDIT
I do receive the access token from the:
authenticationResult = authenticationContext.AcquireToken(
SettingsHelper.ServerName,
new ClientCredential(SettingsHelper.ClientId, SettingsHelper.ClientSecret));
as I can see by debugging the code.
No refresh token is present though, and I don't know if this has something to say?
EDIT
I just managed to debug all my way into the exchange.ResponseHeaders in where I saw this:
The access token is acquired using an authentication method that is
too weak to allow access for this application. Presented auth
strength was 1, required is 2
I decoded the JWT, as this is my result:
{
typ: "JWT",
alg: "RS256",
x5t: "MnC_VZcATfM5pOYiJHMba9goEKY",
kid: "MnC_VZcATfM5pOYiJHMba9goEKY"
}.
{
aud: "https://outlook.office365.com/",
iss: "https://sts.windows.net/d35f5b06-f051-458d-92cc-2b8096b4b78b/",
iat: 1445416753,
nbf: 1445416753,
exp: 1445420653,
ver: "1.0",
tid: "d35f5b06-f051-458d-92cc-2b8096b4b78b",
oid: "c5da9088-987d-463f-a730-2706f23f3cc6",
sub: "c5da9088-987d-463f-a730-2706f23f3cc6",
idp: "https://sts.windows.net/d35f5b06-f051-458d-92cc-2b8096b4b78b/",
appid: "70af108f-5c8c-4ee4-a40f-ab0b6f5922e0",
appidacr: "1"
}.
[signature]
Where to go from here?
I already got this error while using EWS in the past "The access token is acquired using an authentication method that is too weak to allow access for this application. Presented auth strength was 1, required is 2"
What you need to do is to enforce your authentication with a certificate.
AuthenticationContext authContext = new AuthenticationContext(authority);
exchangeService.Credentials = new OAuthCredentials(authContext.AcquireToken("https://outlook.office365.com", new ClientAssertionCertificate(ConfigurationManager.AppSettings["ida:ClientId"], certificate)).AccessToken);
The key part is to define a new ClientAssertionCertificate as you ClientAssertion.
You will also have to modify the manifest of your Azure Active Directory Application.
Looks at this reference (the part about "Configuring a X.509 public cert for your application") : https://msdn.microsoft.com/en-us/office/office365/howto/building-service-apps-in-office-365

picasaweb.google.com OAuth 2.0

We have a problem with the new authentication PicasaWeb
We are using this code in C # .NET 2012 ( Framework 4.5.1 )
const string ServiceAccountEmail = "xxxxxxxxxxxxxxxxxxxx#developer.gserviceaccount.com";
var certificate = new X509Certificate2(#"C:\key.p12", "notasecret", X509KeyStorageFlags.Exportable);
var serviceAccountCredentialInitializer =
new ServiceAccountCredential.Initializer(ServiceAccountEmail)
{
Scopes = new[] { "https://picasaweb.google.com/data/"}
}.FromCertificate(certificate);
var credential = new ServiceAccountCredential(serviceAccountCredentialInitializer);
if (!credential.RequestAccessTokenAsync(System.Threading.CancellationToken.None).Result)
throw new InvalidOperationException("Access token request failed.");
var requestFactory = new GDataRequestFactory(null);
requestFactory.CustomHeaders.Add("Authorization: Bearer " + credential.Token.AccessToken);
requestFactory.CustomHeaders.Add("Gdata-version: 2");
PicasaService service = new PicasaService("api-project");
service.RequestFactory = requestFactory;
PhotoQuery query = new PhotoQuery(PicasaQuery.CreatePicasaUri(_IdUsuari, _albumid));
PicasaFeed feed = service.Query(query);
We have an error to retrieve the PicasaFeed :
Unhandled Exception: Google.GData.Client.GDataRequestException: Execution of aut hentication request returned unexpected result: 404
We've done every step of the link : Google.GData.Client.GDataRequestException - Authentication suddenly fails in old code
But it has not worked , is that we are using 4.5.1 and not 4.5 ?
We have done some testing generating the token from the page of Google : https://developers.google.com/oauthplayground
We selected Picasa Web API v2 with the scope: https://picasaweb.google.com/data/
This has generated a token. We have marked the "Auto -refresh the token before it expires" option as it expires in 3600 seconds .
The question is whether this token changes after 3600 seconds? .
With the token generated from this link we have replaced the previous code , where " XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX " is the token generated :
var requestFactory = new GDataRequestFactory(null);
requestFactory.CustomHeaders.Add("Authorization: Bearer " + "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX");
requestFactory.CustomHeaders.Add("Gdata-version: 2");
PicasaService service = new PicasaService("api-project");
service.RequestFactory = requestFactory;
PhotoQuery query = new PhotoQuery(PicasaQuery.CreatePicasaUri(_IdUsuari, _albumid));
PicasaFeed feed = service.Query(query);
And with this token if it works.
Any thoughts that the first code generated by the token code is not working properly for generating tokens and readings to Picasa.
Does anyone have any solution?
Thank you very much
I only wanted to add, that I have the same problem since May, 25.
Since then the api worked correctly and afterwords I get the 404 (page not found error) too.
Maybe google has changed something.
Because my code look similar! and I don't see any error in your code.
Greetings
Mike

Error Uploading Video to YouTube

I am using following code to upload a video to YouTube.
It always gives following error.
The remote server returned an error: (403) Forbidden.
My Code is
YouTubeRequestSettings settings;
YouTubeRequest request;
string devkey = YouTubeDeveloperKey;
string username = YoutubeUserName;
string password = YoutubePassword;
settings = new YouTubeRequestSettings("VideoEditor", devkey, username, password) { Timeout = -1 };
request = new YouTubeRequest(settings);
Video newVideo = new Video();
newVideo.Title = Title;
newVideo.Description = Description;
newVideo.Private = true;
newVideo.YouTubeEntry.Private = false;
newVideo.YouTubeEntry.MediaSource = new MediaFileSource(FilePath, "video/flv");
Video createdVideo = request.Upload(newVideo);
Please do you have any idea about this error
As per the Youtube API V2 documentation, error 403 is an authorization error.
Most probably the username and password might be wrong.
My guess: Did you enable two step authentication on your Google account ?
If so, you must use an application-specific password.
Try to go to your youtube application via https://console.developers.google.com then select your application go to APIs and auth -> APIs.
It will display a list of multiple available APIs, click on Youtube Data API, and then click "enable". This will enable this API to be used by your app and most likely will solve your issue.

Categories