How to get proxy addresses using https://microsoft.graph.com and GraphServiceClient - microsoft-graph-api

I am trying to obtain proxy addresses, but the proxy addresses property returns null even though proxy addresses exist.
GraphClientHelper graphClientHelper = new GraphClientHelper(tenantId);
GraphServiceClient graphServiceClient = graphClientHelper.GetGraphServiceClient();
IGraphServiceUsersCollectionPage user = await graphServiceClient.Users.Request().GetAsync();
I get proxy addresses using https://windows.net and ActiveDirectoryCLient.

You need to request proxyAddresses specifically.
For example:
var users = await graphClient.Users.Request().Select("id, mail, proxyAddresses").GetAsync();

Related

Exchange Webservice using Oauth throws error when subscribing a resource

I am using OAuth2.0 to connect to Exchange webservices. Everything else seems to work ok for me . However when i try to subscribe one of the room resource by using grouping info and providing the anchor mailbox as one of the primary mail box it throws an error.
"Request failed because EWS could not contact the appropriate CAS server for this request."
So for example i am trying to subscribe nitroom1 and one the primary mailbox associated with the group is nitroom2 which i am using as X-AnchorMailbox then i got the above error.
public static ExchangeService GetExchangeService(string exchangeURL, string userName, string password, string resourceEmail, string primaryMailbox, string clientID, string tenantID, string clientSecret, string certName)
{
ExchangeService service;
service = new ExchangeService(setTZtoUTC);
service.Url = new Uri(exchangeURL);
if (!string.IsNullOrWhiteSpace(clientID) && !string.IsNullOrWhiteSpace(tenantID))
{
string oAuthToken = multiExchangeManager.getOAuthTokenFromCache(clientID, tenantID, clientSecret, certName);
service.Credentials = new OAuthCredentials(oAuthToken);
}
else
{
service.Credentials = new WebCredentials(userName, password);
}
service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, resourceEmail);
service.HttpHeaders.Add("X-AnchorMailbox", primaryMailbox);
service.HttpHeaders.Add("X-PreferServerAffinity", "true");
return service;
}
However if i connect ews using impersonate account then do same thing it works fine.
Also, if i use resourceMailbox same as primary mailbox then it works ok as well.so in my example it will look like this.
service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, "nitroom1");
service.HttpHeaders.Add("X-AnchorMailbox", "nitroom1");
This is how i am trying to use subscription.
exchangeService.SubscribeToStreamingNotifications(
new FolderId[] { WellKnownFolderName.Calendar, WellKnownFolderName.DeletedItems },
EventType.Created, EventType.Deleted, EventType.Modified, EventType.Moved, EventType.Copied);
Does anyone have any idea why its happening or what i am doing wrong here?
one more thing to add, i tried EWSEditor tool which provides subscription info and both above mentioned resources sharing same grouping info.
I think i found a solution for this issue, i just need to set
X-BackEndOverRideCookie with any service used for subscribing child mailbox.
For more info read this article
https://learn.microsoft.com/en-us/exchange/client-developer/exchange-web-services/how-to-maintain-affinity-between-group-of-subscriptions-and-mailbox-server

How to make HttpClient relay traffic show up in Fidder or Charles?

I have a simple web api project based on this example:
http://aspnet.codeplex.com/sourcecontrol/latest#Samples/WebApi/RelaySample/Program.cs
However, in the above sample the relay is working with a local server, in my project the relay is working with an external web server with a real address; companyX.com
I am using the relay service (or, web proxy service) through a browser, for example, in the browser request relayService.com/companyX. The relay service responds with data from the external companyX.com site.
The relay works great, however some headers are not correct and I need to see what the HttpClient is sending to the remote companyX.com server.
In fiddler or Charles, only the request/response from my browser to relayService.com is listed, the request/response from the HttpClient to relayService.com never shows up.
The relayService.com is running locally on my machine, in IIS7, I'm using the hosts file to direct traffic to relayService.com.
I have tried several variation of the following when creating the HttpClient:
var clientHandler = new HttpClientHandler
{
CookieContainer = cookies,
UseCookies = true,
UseDefaultCredentials = false,
Proxy = new WebProxy("http://localhost:8888"),
UseProxy = true,
AutomaticDecompression = DecompressionMethods.GZip,
AllowAutoRedirect = false,
ClientCertificateOptions = ClientCertificateOption.Automatic
};
HttpClient client = new HttpClient(clientHandler);
UPDATE
If I change UseProxy = false The service continues to work, when Fiddler is open or closed.
With UseProxy = true then the service will fail, if fiddler is open, I get the following error:
Object reference not set to an instance of an object.
at System.DomainNameHelper.IdnEquivalent(String hostname) at System.Net.HttpWebRequest.GetSafeHostAndPort(Uri sourceUri, Boolean addDefaultPort, Boolean forcePunycode) at System.Net.HttpWebRequest.GenerateProxyRequestLine(Int32 headersSize) at System.Net.HttpWebRequest.SerializeHeaders() at System.Net.HttpWebRequest.EndSubmitRequest() at System.Net.Connection.CompleteConnection(Boolean async, HttpWebRequest request)
With UseProxy = true and fiddler is CLOSED, I get the following (obvious) error:
No connection could be made because the target machine actively refused it 127.0.0.1:8888
In the same solution I am using HttpWebRequest to download data from the web and that does show up in Fiddler, so it seems to be an issue with the HttpClient.GetAsync()
I have tried this on two machines with identical results.
I have been struggling with this all day, any help would be much appreciated.
Just to recap:
* relayService.com is running locally on my machine, in IIS7
hosts file has "127.0.0.1 relayService.com"
relayService.com is an MVC Web API site that uses HttpClient.GetAsync() to download content from the live web
Fiddler/Charles is running locally on same machine
browser traffic to the local relayService.com appears in Fiddler/Charles
HttpClient.GetAsync() to live web traffic does not appear in Fiddler/Charles
Fiddler/Charles are both up to date versions.
Thanks again
You don't need anything in your HOSTS file if you're using Fiddler; you can use Fiddler's Tools > HOSTS to redirect traffic anywhere you'd like.
When trying to capture traffic from a service account (e.g. the ASP.NET acccount) you typically want to configure that account to use the proxy; see http://fiddler2.com/blog/blog/2013/01/08/capturing-traffic-from-.net-services-with-fiddler for details on that. If you do that, you shouldn't need to configure the proxy object directly in code.
The exception you've shown suggests that here's a bug in the GenerateProxyRequestLine function. Is there any change if you update this: new WebProxy("http://localhost:8888"); to new WebProxy("127.0.0.1", 8888); ?
Generally speaking, .NET applications will bypass the proxy for URLs pointed at //localhost or //127.0.0.1, so when debugging with Fiddler it's common to use a service URL of //localhost.fiddler so that the traffic is always sent to the proxy.
I fixed the problem by making the HttpClient static.
This works fine (for the program functionality) but has the problem with fiddler described above, where trying to use the proxy throws an error:
private HttpClient _client()
{
var clientHandler = new HttpClientHandler
{
UseCookies = true,
UseDefaultCredentials = false,
Proxy = new WebProxy("http://localhost:8888"),
UseProxy = true,
AutomaticDecompression = DecompressionMethods.GZip,
AllowAutoRedirect = true,
ClientCertificateOptions = ClientCertificateOption.Automatic
};
HttpClient client = new HttpClient(clientHandler);
client.Timeout = TimeSpan.FromMinutes(20);
return client;
}
The client was created with:
using (HttpResponseMessage serviceResponse = await _client().GetAsync(getURL(), HttpCompletionOption.ResponseHeadersRead))
{
// Return response
}
However, the below also works and all traffic shows up in Fiddler!
private static readonly HttpClientHandler _clientHandler = new HttpClientHandler()
{
//CookieContainer = cookies,
UseCookies = true,
UseDefaultCredentials = false,
Proxy = new WebProxy("http://localhost:8888"),
UseProxy = false,
AutomaticDecompression = DecompressionMethods.GZip,
AllowAutoRedirect = false,
ClientCertificateOptions = ClientCertificateOption.Automatic,
};
//Create a shared instance of HttpClient and set the request timeout
private static readonly HttpClient _client = new HttpClient(_clientHandler)
{
Timeout = TimeSpan.FromMinutes(20)
};
The client was created with (only difference is removing the '()' after _client above):
using (HttpResponseMessage serviceResponse = await _client.GetAsync(getURL(), HttpCompletionOption.ResponseHeadersRead))
{
// Return response
}
I have no clue why this works. Any insight would be appreciated.
Thanks,

How to include network credentials in Neo4JClient?

So tipically if you install Neo4j in your development environment, you will have a local hosted version of the Neo4Jserver, which usually you can browse with: localhost:7474/db/data.
Your code is like this:
var client = new GraphClient(new Uri("http://localhost:7474/db/data"));
client.Connect();
However, one day you will want to connect to your Cloud-based Neo4J Server (Heroku, Azure, etc.)
Of course, that means you will have to provide Network credentials.
If you only use your bare hands, it could be like this:
var http = (HttpWebRequest)WebRequest.Create(new Uri("http://<<your_REST_query"));
var cred = new NetworkCredential("yourusername", "yourpassword");
http.Credentials = cred;
var response = http.GetResponse();
var stream = response.GetResponseStream();
But how can I include network credentials to connect with Neo4JClient? or is there another option that I don't know?
We support the standard URI syntax for basic authentication credentials:
var client = new GraphClient(new Uri("http://user:pass#localhost:7474/db/data"));
From version 1.1.0.0
var username = "app_username"
var password = "1#mGr#phG0d"
var client = new GraphClient(new Uri("http://localhost:7474/db/data"), username, password);

GetClientAccessToken having clientIdentifier overwritten to null by NetworkCredential

I've been trying to get the GetClientAccessToken flow to work with the latest release 4.1.0 (via nuget), where I'm in control of all three parties: client, authorization server and resource server.
The situation I have started to prototype is that of a Windows client app (my client - eventually it will be WinRT but its just a seperate MVC 4 app right now to keep it simple), and a set of resources in a WebAPI project. I'm exposing a partial authorization server as a controller in the same WebAPI project right now.
Every time (and it seems regardless of the client type e.g. UserAgentClient or WebServerClient) I try GetClientAccessToken, by the time the request makes it to the auth server there is no clientIdentifier as part of the request, and so the request fails with:
2012-10-15 13:40:16,333 [41 ] INFO {Channel} Prepared outgoing AccessTokenFailedResponse (2.0) message for <response>:
error: invalid_client
error_description: The client secret was incorrect.
I've debugged through the source into DNOA and essentially the credentials I'm establishing on the client are getting wiped out by NetworkCredential.ApplyClientCredential inside ClientBase.RequestAccessToken. If I modify clientIdentifier to something reasonable, I can track through the rest of my code and see the correct lookups/checks being made, so I'm fairly confident the auth server code is ok.
My test client currently looks like this:
public class AuthTestController : Controller
{
public static AuthorizationServerDescription AuthenticationServerDescription
{
get
{
return new AuthorizationServerDescription()
{
TokenEndpoint = new Uri("http://api.leave-now.com/OAuth/Token"),
AuthorizationEndpoint = new Uri("http://api.leave-now.com/OAuth/Authorise")
};
}
}
public async Task<ActionResult> Index()
{
var wsclient = new WebServerClient(AuthenticationServerDescription, "KieranBenton.LeaveNow.Metro", "testsecret");
var appclient = new DotNetOpenAuth.OAuth2.UserAgentClient(AuthenticationServerDescription, "KieranBenton.LeaveNow.Metro", "testsecret");
var cat = appclient.GetClientAccessToken(new[] { "https://api.leave-now.com/journeys/" });
// Acting as the Leave Now client we have access to the users credentials anyway
// TODO: CANNOT do this without SSL (turn off the bits in web.config on BOTH sides)
/*var state = client.ExchangeUserCredentialForToken("kieranbenton", "password", new[] { "https://api.leave-now.com/journeys/" });
// Attempt to talk to the APIs WITH the access token
var resourceclient = new OAuthHttpClient(state.AccessToken);
var response = await resourceclient.GetAsync("https://api.leave-now.com/journeys/");
string sresponse = await response.Content.ReadAsStringAsync();*/
// A wrong one
/*var wresourceclient = new OAuthHttpClient("blah blah");
var wresponse = await wresourceclient.GetAsync("https://api.leave-now.com/journeys/");
string wsresponse = await wresponse.Content.ReadAsStringAsync();
// And none
var nresourceclient = new HttpClient();
var nresponse = await nresourceclient.GetAsync("https://api.leave-now.com/journeys/");
string nsresponse = await nresponse.Content.ReadAsStringAsync();*/
return Content("");
}
}
I can't figure out how to prevent this or if its by design what I'm doing incorrectly.
Any help appreciated.
The NetworkCredentialApplicator clears the client_id and secret from the outgoing message as you see, but it applies it as an HTTP Authorization header. However, HttpWebRequest clears that header on the way out, and only restores its value if the server responds with an HTTP error and a WWW-Authenticate header. It's quite bizarre behavior on .NET's part, if you ask me, to suppress the credential on the first outbound request.
So if the response from the auth server is correct (at least, what the .NET client is expecting) then the request will go out twice, and work the second time. Otherwise, you might try using the PostParameterApplicator instead.

Get Client Machine ID

I need to get Client's Machine ID and their Country in my web application...
Is it possible get succeed in this?
using System.Globalization;
string culture = CultureInfo.CurrentCulture.EnglishName;
string country = culture.Substring(culture.IndexOf('(')
+ 1, culture.LastIndexOf(')') - culture.IndexOf('(')-
Client Country in C#
Get Client Computer Name,
How to get the client machine name from a server
You will get most of the details of
the client machine using the
"Request.ServerVariables"
// Try the following C# code
System.Net.IPHostEntry host = new System.Net.IPHostEntry();
host = System.Net.Dns.GetHostByAddress(Request.ServerVariables["REMOTE_HOST"]);
lbl.Text = host.HostName;
Host name:
Request.ServerVariables["REMOTE_HOST"]
See http://www.w3schools.com/asp/coll_servervariables.asp
Resolve country:
public static RegionInfo ResolveCountry()
{
CultureInfo culture = ResolveCulture();
if (culture != null)
return new RegionInfo(culture.LCID);
return null;
}
from http://madskristensen.net/post/Get-language-and-country-from-a-browser-in-ASPNET.aspx
This uses the PC's setup Language/Country.
By IP try an example at:
http://dotnetguts.blogspot.com/2008/06/finding-country-from-visitors-ip-in.html
Which involves checking the requesting IP adresses against a database of IP locations.
You could also use an IP for a service that already supports this such as:
http://www.ipgeo.com/api/

Resources