Working C# code converted to Powershell results in SocketException - azure

I have the following C# console app which successfully calls an HTTP Post endpoint:
class Program
{
static void Main(string[] args)
{
HttpClient httpClient = new HttpClient();
httpClient.BaseAddress = new Uri("https://DomainOne.azure-api.net");
httpClient.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "8b17badbbfe44e9e933453a8b4d8fc85");
StringContent stringContent = new StringContent("\"hi\"", System.Text.Encoding.UTF8, "application/json");
Task<HttpResponseMessage> task = httpClient.PostAsync("integration/api/Result/CompanyOne", stringContent);
HttpResponseMessage response = task.Result;
var content = response.Content.ReadAsStringAsync().Result;
}
}
This is the equivalent Powershell script I'm trying to use:
$httpClient = New-Object 'System.Net.Http.HttpClient'
$httpClient.BaseAddress = New-Object 'System.Uri'('https://DomainOne.azure-api.net')
$httpClient.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "8b17badbbfe44e9e933453a8b4d8fc85");
$stringContent = New-Object 'System.Net.Http.StringContent'('"hi"', [System.Text.Encoding]::UTF8, 'application/json')
$task = $httpClient.PostAsync('integration/api/Result/CompanyOne', $stringContent)
$response = $task.Result
$content = $response.Content.ReadAsStringAsync().Result
However the $task object contains the following:
System.AggregateException: One or more errors occurred.
---> System.Net.Http.HttpRequestException: An error occurred while sending the request.
---> System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send.
---> System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.
---> System.Net.Sockets.SocketException: An existing connection was forcibly closed by the remote host
at System.Net.Sockets.Socket.EndReceive(IAsyncResult asyncResult)
at System.Net.Sockets.NetworkStream.EndRead(IAsyncResult asyncResult)
--- End of inner exception stack trace ---
at System.Net.TlsStream.EndWrite(IAsyncResult asyncResult)
at System.Net.ConnectStream.WriteHeadersCallback(IAsyncResult ar)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.EndGetRequestStream(IAsyncResult asyncResult, TransportContext& context)
at System.Net.Http.HttpClientHandler.GetRequestStreamCallback(IAsyncResult ar)
--- End of inner exception stack trace ---
The endpoint is hosted in our dev Azure environment behind API Management, and the action method/controller looks like this:
[ApiController]
[Route("api/[controller]")]
public class ResultController : ControllerBase
{
[Route("{providerName}")]
[HttpPost]
public Task<bool> ReceiveMessage(HL7Message message)
{
return Task.FromResult(true);
}
}
Here are the protocol settings in Azure API Management:
Why am I getting the SocketException in Powershell but not in C#, and how can I get it to work in Powershell?

Based on Rick Rainey's helpful comment, you can force the TLS version by adding the line of code below before the HTTP call:
[System.Net.ServicePointManager]::SecurityProtocol = [System.Net.SecurityProtocolType]::Tls12
I believe this to be a limitation of the .NET version being used. Any version below .NET 4.6 will default to using a TLS version that is not 1.2.

Related

RBAC issues using MassTransit with Azure service bus and MSI authentication

We are using MassTransit (v.5.5.5) with Azure Service Bus in a .net core v.2.2 application running in a container within Kubernetes. During the Bus setup we create a token using the managed service identity (MSI), like this...
var tokenProvider = TokenProvider.CreateManagedServiceIdentityTokenProvider();
var busControl = Bus.Factory.CreateUsingAzureServiceBus(cfg =>
{
IServiceBusHost busHost = cfg.Host(new Uri(Settings.Host), h =>
{
h.OperationTimeout = TimeSpan.FromSeconds(5);
h.TokenProvider = tokenProvider;
h.TransportType = Settings.TransportType;
});
...
}
Within Azure, the MSI is configured with all 3 Service Bus permissions (Owner, Sender and Receiver) - as decribed here.
When the application starts authentication seems to happen successfully but when MassTransit begins to listen on the specific queues we create it fails with the following error:
MassTransit.Azure.ServiceBus.Core.Transport.ReceiveTransport Error: 0 :
ReceiveTransport Faulted: sb://hostname.servicebus.windows.net/some-custom-queue,
Microsoft.Azure.ServiceBus.UnauthorizedException: Generic: Failed during RBAC check,
please make sure service resource provider is registered on your tenant.
Points to note:
The application does create the temporary bus queue, and there are no errors to do with accessing it.
The application does not create our custom queues.
If the MSI permissions are removed then no queues are created and the error is different: Authorization failed for specified action: Manage,EntityWrite.
For what it's worth we are using the AmqpWebSockets transport type.
It seems weird that the temporary queue is created but not our application-specific ones.
So I guess my question is this... have I done anything wrong or is this something that is not yet available for MassTransit using Service Bus with MSI?
Thanks in advance.
We came across the same issue. We are using Mass Transit 6.* and Azure Service Bus. When switched to MSI we start see the same error:
Microsoft.Azure.ServiceBus.UnauthorizedException: Generic: Failed during RBAC check, please make sure service resource provider is registered on your tenant. TrackingId:2644d62a-83a9-444f-8aeb-b4bdee2fa84d_G30, SystemTracker:NoSystemTracker, Timestamp:2020-02-13T15:54:49
at Microsoft.Azure.ServiceBus.Management.ManagementClient.SendHttpRequest(HttpRequestMessage request, CancellationToken cancellationToken)
at Microsoft.Azure.ServiceBus.Management.ManagementClient.PutEntity(String path, String requestBody, Boolean isUpdate, String forwardTo, String fwdDeadLetterTo, CancellationToken cancellationToken)
at Microsoft.Azure.ServiceBus.Management.ManagementClient.CreateTopicAsync(TopicDescription topicDescription, CancellationToken cancellationToken)
at MassTransit.Azure.ServiceBus.Core.Contexts.NamespaceManager.<>c__DisplayClass25_0`1.<<RunOperation>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.Azure.ServiceBus.RetryPolicy.RunOperation(Func`1 operation, TimeSpan operationTimeout)
at Microsoft.Azure.ServiceBus.RetryPolicy.RunOperation(Func`1 operation, TimeSpan operationTimeout)
at MassTransit.Azure.ServiceBus.Core.Contexts.NamespaceManager.RunOperation[T](Func`1 operation)
at MassTransit.Azure.ServiceBus.Core.Contexts.ServiceBusNamespaceContext.CreateTopic(TopicDescription topicDescription)
at MassTransit.Azure.ServiceBus.Core.Pipeline.ConfigureTopologyFilter`1.ConfigureTopology(NamespaceContext context)
at MassTransit.Azure.ServiceBus.Core.Pipeline.ConfigureTopologyFilter`1.<>c__DisplayClass5_0.<<Send>b__0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at GreenPipes.PipeExtensions.OneTimeSetup[T](PipeContext context, Func`2 setupMethod, PayloadFactory`1 payloadFactory)
at MassTransit.Azure.ServiceBus.Core.Pipeline.ConfigureTopologyFilter`1.Send(NamespaceContext context, IPipe`1 next)
at GreenPipes.Agents.AsyncPipeContextPipe`1.Send(TContext context)
at GreenPipes.Agents.PipeContextSupervisor`1.GreenPipes.IPipeContextSource<TContext>.Send(IPipe`1 pipe, CancellationToken cancellationToken)
at GreenPipes.Agents.PipeContextSupervisor`1.GreenPipes.IPipeContextSource<TContext>.Send(IPipe`1 pipe, CancellationToken cancellationToken)
at GreenPipes.Agents.PipeContextSupervisor`1.GreenPipes.IPipeContextSource<TContext>.Send(IPipe`1 pipe, CancellationToken cancellationToken)
at MassTransit.Azure.ServiceBus.Core.Pipeline.JoinContextFactory`3.<>c__DisplayClass7_0.<<CreateJoinContext>g__Join|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at MassTransit.Azure.ServiceBus.Core.Pipeline.ClientContextFactory.CreateSharedContext(Task`1 context, CancellationToken cancellationToken)
at GreenPipes.Agents.PipeContextSupervisor`1.GreenPipes.IPipeContextSource<TContext>.Send(IPipe`1 pipe, CancellationToken cancellationToken)
at GreenPipes.Agents.PipeContextSupervisor`1.GreenPipes.IPipeContextSource<TContext>.Send(IPipe`1 pipe, CancellationToken cancellationToken)
at GreenPipes.Agents.PipeContextSupervisor`1.GreenPipes.IPipeContextSource<TContext>.Send(IPipe`1 pipe, CancellationToken cancellationToken)
at MassTransit.Azure.ServiceBus.Core.Transport.ReceiveTransport.<Receiver>b__12_0()
at MassTransit.Azure.ServiceBus.Core.Pipeline.JoinContextFactory`3.<>c__DisplayClass7_0.<<CreateJoinContext>g__Join|0>d.MoveNext()
Finally we found that ASB Sdk Microsoft.Azure.ServiceBus.Management.ManagementClient doesn't allow to create topics with slashes in path when tokens from MSI used. This code below return the same error:
try
{
var address = "sb://[name].servicebus.windows.net";
var tokenProvider = new TokenProvider.CreateManagedIdentityTokenProvider();();
var _managementClient = new ManagementClient(address.ToString(), tokenProvider);
var topicDefinition = new TopicDescription("myNewTopic/22222");
await _managementClient.CreateTopicAsync(topicDefinition);
}
catch (Exception e)
{
Debug.WriteLine(e);
throw;
}
Since MT uses special naming convention to setup messaging topology, we get topic path with namespace of particular message type. If we have message MassTransitTest.Message1 it will be converted to topic MassTransitTest/Message1 (with slash). To fix this we setup our own IEntityNameFormatter
public class MyEntityNameFormatter : IEntityNameFormatter
{
readonly IMessageNameFormatter _formatter;
public MyEntityNameFormatter()
{
_formatter = new ServiceBusMessageNameFormatter();
}
public string FormatEntityName<T>()
{
var entityName = _formatter.GetMessageName(typeof(T)).ToString().Replace("/",".");
return entityName;
}
}
and then
var bus = Bus.Factory.CreateUsingAzureServiceBus(configurator =>
{
...
configurator.MessageTopology.SetEntityNameFormatter(new MyEntityNameFormatter());
...
This fixed our issue. (We tried use ~ instead of . but got some validation errors, so decided use dots)
I have been able to reproduce the same error using Azure Service Bus SDK code directly in a .NET Core (3.0) ASP.NET application hosted in an AppService with Managed Identity.
string serviceBusNamespace = "busnamespace_here";
string queueName = "with_service_name/test"; // NOT working with RBAC
// string queueName = "testrbac"; // Works with RBAC - no /
var msiTokenProvider = TokenProvider.CreateManagedIdentityTokenProvider();
var qc = new QueueClient(new Uri($"sb://{serviceBusNamespace}.servicebus.windows.net/").ToString(), queueName, msiTokenProvider);
var message = new Message(Encoding.UTF8.GetBytes($"Test {DateTime.Now.ToShortTimeString()}"))
{
ContentType = "application/text",
Label = "Scientist",
MessageId = Guid.NewGuid().ToString()
};
try
{
await qc.SendAsync(message);
}
catch (Exception ex)
{
return View(ex.ToString());
}
I found out that the error seems to be caused by the presence of a / in the queue name. It's a character that is allowed in the Service Bus but it doesn't seems to works quite nicely with RBAC Service Bus feature.
The same code works well if you use a SAS Policy instead of Managed Identity/Client Secret.
Here is my test Service Bus in image (using Service Bus Explorer) :
Mass Transit
I know Mass Transit can use entity path with slash character in it. Does that means we can't use RBAC to access those entities ?
I wasn't able to find what is the root cause.

Azure Function App Container Failing to Start at Minikube Container Error: The listener for function 'EventHubCSharpFunc' was unable to start

I created a very simple Azure functionApp using visual Studio Code which does nothing fancy but logs the received message(Function App listen to Eventhub message in Azure). This works and get hosted well when i debug the function app locally. However, when I publish this into minikube as container, it throws below error:
The listener for function 'EventHubCSharpFunc' was unable to start.
Microsoft.Azure.WebJobs.Host.Listeners.FunctionListenerException: The listener for function 'EventHubCSharpFunc' was unable to start. ---> Microsoft.Azure.EventHubs.Processor.EventProcessorConfigurationException: Encountered error while fetching the list of EventHub PartitionIds ---> System.Net.Sockets.SocketException: Resource temporarily unavailable
at Microsoft.Azure.EventHubs.Amqp.AmqpEventHubClient.CreateConnectionAsync(TimeSpan timeout)
at Microsoft.Azure.Amqp.FaultTolerantAmqpObject`1.OnCreateAsync(TimeSpan timeout)
at Microsoft.Azure.Amqp.Singleton`1.CreateValue(TaskCompletionSource`1 tcs, TimeSpan timeout)
at Microsoft.Azure.Amqp.Singleton`1.GetOrCreateAsync(TimeSpan timeout)
at Microsoft.Azure.EventHubs.Amqp.Management.AmqpServiceClient.OpenRequestResponseLinkAsync(String type, String address, Nullable`1 entityType, String[] requiredClaims, TimeSpan timeout)
at Microsoft.Azure.EventHubs.Amqp.Management.AmqpServiceClient.OpenLinkAsync(TimeSpan timeout)
at Microsoft.Azure.Amqp.FaultTolerantAmqpObject`1.OnCreateAsync(TimeSpan timeout)
at Microsoft.Azure.Amqp.Singleton`1.CreateValue(TaskCompletionSource`1 tcs, TimeSpan timeout)
at Microsoft.Azure.Amqp.Singleton`1.GetOrCreateAsync(TimeSpan timeout)
at Microsoft.Azure.EventHubs.Amqp.Management.AmqpServiceClient.GetRuntimeInformationAsync()
at Microsoft.Azure.EventHubs.Amqp.AmqpEventHubClient.OnGetRuntimeInformationAsync()
at Microsoft.Azure.EventHubs.EventHubClient.GetRuntimeInformationAsync()
at Microsoft.Azure.EventHubs.Processor.PartitionManager.GetPartitionIdsAsync()
--- End of inner exception stack trace ---
at Microsoft.Azure.EventHubs.Processor.PartitionManager.GetPartitionIdsAsync()
at Microsoft.Azure.EventHubs.Processor.PartitionManager.GetPartitionIdsAsync()
at Microsoft.Azure.EventHubs.Processor.PartitionManager.InitializeStoresAsync()
at Microsoft.Azure.EventHubs.Processor.PartitionManager.StartAsync()
at Microsoft.Azure.EventHubs.Processor.EventProcessorHost.RegisterEventProcessorFactoryAsync(IEventProcessorFactory factory, EventProcessorOptions processorOptions)
at Microsoft.Azure.WebJobs.EventHubs.EventHubListener.StartAsync(CancellationToken cancellationToken) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Extensions.EventHubs\Listeners\EventHubListener.cs:line 46
at Microsoft.Azure.WebJobs.Host.Listeners.FunctionListener.StartAsync(CancellationToken cancellationToken, Boolean allowRetry) in C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Listeners\FunctionListener.cs:line 68
I tried to check if my cluster is having internet access, but I am successfully able to ping internet IP from other containers in minikube.
public static class EventHubCSharpFunc
{
[FunctionName("EventHubCSharpFunc")]
public static async Task Run([EventHubTrigger("containertestevthub", Connection = "EventGridPerfEventHun_RootManageSharedAccessKey_EVENTHUB")] EventData[] events, ILogger log)
{
var exceptions = new List<Exception>();
foreach (EventData eventData in events)
{
try
{
string messageBody = Encoding.UTF8.GetString(eventData.Body.Array, eventData.Body.Offset, eventData.Body.Count);
// Replace these two lines with your processing logic.
log.LogInformation($"C# Event Hub trigger function processed a message: {messageBody}");
await Task.Yield();
}
catch (Exception e)
{
// We need to keep processing the rest of the batch - capture this exception and continue.
// Also, consider capturing details of the message that failed processing so it can be processed again later.
exceptions.Add(e);
}
}
// Once processing of the batch is complete, if any messages in the batch failed processing throw an exception so that there is a record of the failure.
if (exceptions.Count > 1)
throw new AggregateException(exceptions);
if (exceptions.Count == 1)
throw exceptions.Single();
}
}
looking into "EventHubCSharpFunc was unable to start" and "Resource temporarily unavailable", please try to connect from Your APP POD to Eventhub.
Please verify if your connection and credentials are working inside Your APP POD.
You can find more about how to pass credentials as Secrets into your POD or Create a Secret based on existing Docker credentials here and here.
For troubleshooting purposes please use those below commands to get more information from your cluster:
kubectl log <your_pod_with_application>
kubectl describe <your_pod_with_application>
kubectl get events
kubectl get all --all-namespaces

Why am I getting javax.xml.bind.UnmarshalException when calling a soap web service

I am trying consume a SOAP web Service and I have written my SOAP client using Spring-ws. This also included a message signing. However when I am trying to trigger a request I am getting the exception. From the server standpoint, the server is sending a successful response but I am not able to unmarshall it.
I followed quite a few suggestion including one from this
UnmarshallingFailureException, unexpected element (uri:"http://schemas.xmlsoap.org/soap/envelope/", local:"Fault")
Following the above link however removed the exception but in turn I am getting a null response object and I could not trace out where the response went missing.
This is my Config class methods:
public WebServiceTemplate accountsInquiryWebServiceTemplate() throws Exception {
WebServiceTemplate webServiceTemplate = new WebServiceTemplate();
Jaxb2Marshaller accountsInquiryMarshaller = accountsInquiryMarshaller();
webServiceTemplate.setMarshaller(accountsInquiryMarshaller);
webServiceTemplate.setUnmarshaller(accountsInquiryMarshaller);
ClientInterceptor[] clientInterceptors = new ClientInterceptor[1];
clientInterceptors[0] = wsClientSecurityInterceptor();
webServiceTemplate.setInterceptors(clientInterceptors);
webServiceTemplate.setCheckConnectionForFault(true);
webServiceTemplate.setDefaultUri(serviceURL);
return webServiceTemplate;
}
private Jaxb2Marshaller accountsInquiryMarshaller() {
Jaxb2Marshaller jaxb2Marshaller = new Jaxb2Marshaller();
jaxb2Marshaller.setContextPaths(new String[]{
"com.accounting.integrationservice"
});
return jaxb2Marshaller;
}
private Wss4jSecurityInterceptor wsClientSecurityInterceptor() throws Exception {
Wss4jSecurityInterceptor wss4jSecurityInterceptor = new Wss4jSecurityInterceptor();
wss4jSecurityInterceptor.setSecurementActions("Signature");
wss4jSecurityInterceptor.setSecurementUsername(username);
wss4jSecurityInterceptor.setSecurementPassword(password);
wss4jSecurityInterceptor.setSecurementSignatureCrypto(clientCrypto());
wss4jSecurityInterceptor.setValidationActions("Signature");
return wss4jSecurityInterceptor;
}
private Crypto clientCrypto() throws Exception {
CryptoFactoryBean cryptoFactoryBean = new CryptoFactoryBean();
cryptoFactoryBean.setKeyStoreLocation(resourceLoader.getResource("classpath:accountsInquiry/keystore/" + keyStoreLocation));
cryptoFactoryBean.setKeyStorePassword(keyStorePassword);
cryptoFactoryBean.afterPropertiesSet();
return cryptoFactoryBean.getObject();
}
The client calls as below:
Response response = accountsWebServiceTemplate.marshalSendAndReceive(request);
The exception stack that I am getting is as below : Its similar to the referred link above, so not putting the entire exception stack
org.springframework.ws.soap.security.AbstractWsSecurityInterceptor.handleResponse(AbstractWsSecurityInterceptor.java:247)
- Could not validate request: No WS-Security header found
org.springframework.oxm.UnmarshallingFailureException: JAXB unmarshalling exception; nested exception is javax.xml.bind.UnmarshalException: unexpected element (uri:"http://schemas.xmlsoap.org/soap/envelope/", local:"Fault"). Expected elements are http://www.qualityaccounts.com/IntegrationService/schemas/ProductInfo/v1}
at org.springframework.oxm.jaxb.Jaxb2Marshaller.convertJaxbException(Jaxb2Marshaller.java:911)
at org.springframework.oxm.jaxb.Jaxb2Marshaller.unmarshal(Jaxb2Marshaller.java:784)
at org.springframework.ws.support.MarshallingUtils.unmarshal(MarshallingUtils.java:62)
at org.springframework.ws.client.core.WebServiceTemplate$3.extractData(WebServiceTemplate.java:413)
at org.springframework.ws.client.core.WebServiceTemplate.doSendAndReceive(WebServiceTemplate.java:619)
at org.springframework.ws.client.core.WebServiceTemplate.sendAndReceive(WebServiceTemplate.java:555)
at org.springframework.ws.client.core.WebServiceTemplate.marshalSendAndReceive(WebServiceTemplate.java:390)
at org.springframework.ws.client.core.WebServiceTemplate.marshalSendAndReceive(WebServiceTemplate.java:383)
Ok So, I was trying to use "Signature" to validate the Security Header of the response even though there was no header. But thing is if I didn't specify the ValidationAction it was throwing NullPointerException so it was expecting at least one ValidationAction.
To counter all this I told the Spring security not to validate the response by this piece of code.
wss4jSecurityInterceptor.setValidateResponse(false);
Thanks to this article
Spring Security - Wss4jSecurityInterceptor - Nullpointer

An unhandled exception has occurred: Malformed URL in Release mode in .net core 2.0 app

I have a .net core 2.0 app which uses IdentityServer 4. it works perfectly in development mode. then I published it for production mode and tested. when I click a (that action has a method to generated accesstoken) link I got an error like below,
An unhandled exception has occurred: Malformed URL
then error occurs here in production(Release) mode:
var disco = await IdentityModel.Client.DiscoveryClient.GetAsync(_configuration.GetSection("Settings").GetSection("DiscoveryClient").Value);
above DiscoveryClient is http not https
here is the full description of the error ..
Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[0]
An unhandled exception has occurred: Malformed URL
System.InvalidOperationException: Malformed URL
at IdentityModel.Client.DiscoveryClient.ParseUrl(String input)
at IdentityModel.Client.DiscoveryClient..ctor(String authority, HttpMessageHandler innerHandler)
at IdentityModel.Client.DiscoveryClient.<GetAsync>d__1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
is this because 'https'. I have no idea what is happening.hope your help with this.
This is a pretty old post, but it still might help someone. I had this exact same issue, only that the URL that I was passing in was perfectly fine. The problem on my side was that the IdentityServer Authority URL was misconfigured, causing it to throw the same exception.
Here is code snippet from DiscoveryClient's ParseUrl showing when it throws that exception:
public static DiscoveryEndpoint ParseUrl(string input)
{
var success = Uri.TryCreate(input, UriKind.Absolute, out var uri);
if (success == false)
{
throw new InvalidOperationException("Malformed URL");
}
if (!DiscoveryEndpoint.IsValidScheme(uri))
{
throw new InvalidOperationException("Malformed URL");
}
Here is the code for DiscoveryEndpoint's IsValidScheme method:
public static bool IsValidScheme(Uri url)
{
if (string.Equals(url.Scheme, "http", StringComparison.OrdinalIgnoreCase) ||
string.Equals(url.Scheme, "https", StringComparison.OrdinalIgnoreCase))
{
return true;
}
return false;
}
Based on this the exception is not thrown because the url is using http.
Try calling
new Uri(_configuration.GetSection("Settings").GetSection("DiscoveryClient").Value, UriKind.Absolute)
before your call to 'IdentityModel.Client.DiscoveryClient.GetAsync' so that you can see what exception is thrown by the Uri constructor.

Calling EWS services through Managed API by using Oauth (ADAL azure active directory library) 401 Unauthorized

I am developing a Provider hosted app in sharepoint for calling EWS services. I am using managed api.
below is my code,
ClientCredential cc = new ClientCredential("********-****-****-****-********e042", "b/2i******n07QKJ********0uhVVvv*****BUs=");
AuthenticationContext authenticationContext = new AuthenticationContext("https://login.windows.net/mydomain.onmicrosoft.com/");
AuthenticationResult result = authenticationContext.AcquireToken("https://outlook.office365.com/", cc);
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013);
service.Credentials = new OAuthCredentials(result.AccessToken);
service.Url = new Uri("https://outlook.office365.com/EWS/Exchange.asmx");
CalendarView calView = new CalendarView(DateTime.Today, DateTime.Today.AddHours(24));
Mailbox m = new Mailbox("xxxx#xxxxxxxx.onmicrosoft.com");
FolderId CalendarFolderId = new FolderId(WellKnownFolderName.Calendar, m);
FindItemsResults<Appointment> master = service.FindAppointments(CalendarFolderId, calView);
The error that i am getting is 401 unauthorized..
following is the stack trace,
The remote server returned an error: (401) Unauthorized.
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.Net.WebException: The remote server returned
an error: (401) Unauthorized.
Source Error: An unhandled exception was generated during the execution of the
current web request. Information regarding the origin and location of
the exception can be identified using the exception stack trace below.
Stack Trace:
[WebException: The remote server returned an error: (401) Unauthorized.]
System.Net.HttpWebRequest.GetResponse() +6540964
Microsoft.Exchange.WebServices.Data.EwsHttpWebRequest.Microsoft.Exchange.WebServices.Data.IEwsHttpWebRequest.GetResponse() +29
Microsoft.Exchange.WebServices.Data.ServiceRequestBase.GetEwsHttpWebResponse(IEwsHttpWebRequest request) +34
[ServiceRequestException: The request failed. The remote server returned an error: (401) Unauthorized.]
Microsoft.Exchange.WebServices.Data.ServiceRequestBase.GetEwsHttpWebResponse(IEwsHttpWebRequest request) +149
Microsoft.Exchange.WebServices.Data.ServiceRequestBase.ValidateAndEmitRequest(IEwsHttpWebRequest& request) +407
Microsoft.Exchange.WebServices.Data.MultiResponseServiceRequest`1.Execute() +36
Microsoft.Exchange.WebServices.Data.ExchangeService.FindItems(IEnumerable`1 parentFolderIds, SearchFilter searchFilter, String queryString, ViewBase view, Grouping groupBy, ServiceErrorHandling errorHandlingMode) +263
Microsoft.Exchange.WebServices.Data.ExchangeService.FindAppointments(FolderId parentFolderId, CalendarView calendarView) +62
SharePointApp2Web.Pages.Default.Page_Load(Object sender, EventArgs e) +1004
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +51
System.Web.UI.Control.OnLoad(EventArgs e) +92
System.Web.UI.Control.LoadRecursive() +54
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +772
Any thoughts on this will be helpful.
thanks in advance

Resources