Any idea why Facebook Provider fails in the below code? - facebook

I implemented OAUTH login with Facebook for my WebAPi service and I am getting the token with the below method:
private static async Task<ExternalLoginData> FromToken(string provider, string accessToken)
{
if (string.IsNullOrEmpty(provider))
return null;
provider = provider.Trim().ToLower();
string verifyTokenEndPoint = "", verifyAppEndpoint = "";
HttpClient client = new HttpClient();
if (provider == ProviderConstants.Facebook)
{
verifyTokenEndPoint = $"https://graph.facebook.com/me?access_token={accessToken}";
verifyAppEndpoint = $"https://graph.facebook.com/app?access_token={accessToken}";
}
else
{
return null;
}
Uri uri = new Uri(verifyTokenEndPoint);
HttpResponseMessage response = await client.GetAsync(uri); <-- exception thrown here
if (response.IsSuccessStatusCode)
{
//not relevant
}
//not relevant
}
The exception is not thrown on local development server on any configuration. But it fails on the live server with the below error.
Any idea why?
Failed when generating token
System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: Unable to connect to the remote server ---> System.Net.Sockets.SocketException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 1.1.1.1:443
at System.Net.Sockets.Socket.EndConnect(IAsyncResult asyncResult)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)
--- End of inner exception stack trace ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at FishingApp.Controllers.AccountController.<FromToken>d__32.MoveNext() in E:\TeamCity\buildAgent\work\22810208a40a1b66\src\FishingApp\Controllers\AccountController.cs:line 1033
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at FishingApp.Controllers.AccountController.<LoginExternalToken>d__30.MoveNext() in E:\TeamCity\buildAgent\work\22810208a40a1b66\src\FishingApp\Controllers\AccountController.cs:line 865
Additional information: looks like I can't connect to the url because I get this error: Unable to connect to the remote server

I was having the same problem since last 5 days, had seen your question 2 days back but that time i didn't had the answer.
Solution:
May be you are using Smarterasp.net as your hosting provider.
They introduced an additional setting in "Security Tab" , where they are rejecting any internal connection going to graph.facebook.com by default. But if you need this, you have to "Enable" this setting.
Smarterasp Snapshot
Good Luck

Related

Acquire access token from Azure AD using username and password for Azure DevOps REST Api

We are implementing AD registered application (deployed as Azure App Service) to access Azure DevOps Rest Api, I have followed the authentication guidance provided for Azure DevOps and using authentication context acquire access token by sending username and password. Although MS is not recommending this authentication process, the reason we are doing this is the user account has permissions to specific access on multiple projects in different organizations. This way we obtain token for that user and access Azure DevOps REST Api's accessible to the user. Basically we created a generic user account that can access DevOps REST Api's from my application.
In the local environment, I am able to get the access token for the user using below code,
AuthenticationContext ctx = new AuthenticationContext("https://login.microsoftonline.com/org.onmicrosoft.com/");
AuthenticationResult result = null;
var username = "********"; // This is your AAD username in the form user#domain.com.
var password = "********"; // This is your AAD password.
var adalCredential = new UserPasswordCredential(username, password);
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
try
{
result = ctx.AcquireTokenAsync(azureDevOpsResourceId, clientId, adalCredential).Result;
Console.WriteLine("Token expires on: " + result.ExpiresOn);
}
catch (Exception ex)
{
Console.WriteLine("{0}: {1}", ex.GetType(), ex.Message);
}
The same code while accessing through the web application is not working as expected, and throws below ADAL Exception,
System.AggregateException: One or more errors occurred. ---> Microsoft.IdentityModel.Clients.ActiveDirectory.AdalException: parsing_wstrust_response_failed: Parsing WS-Trust response failed
at Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.WsTrust.WsTrustResponse.CreateFromResponseDocument(XDocument responseDocument, WsTrustVersion version)
at Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.WsTrust.WsTrustRequest.<SendRequestAsync>d__3.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
at Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Flows.AcquireTokenNonInteractiveHandler.<PreTokenRequestAsync>d__5.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
at Microsoft.IdentityModel.Clients.ActiveDirectory.Internal.Flows.AcquireTokenHandlerBase.<RunAsync>d__57.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext.<AcquireTokenCommonAsync>d__37.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContextIntegratedAuthExtensions.<AcquireTokenAsync>d__0.MoveNext()
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
at System.Threading.Tasks.Task`1.get_Result()
Why is this error, parsing_wstrust_response_failed is occurring when run from the application? I also wanted to know is the approach we are following is correct? do we have an alternate solution that can be implemented to achieve what we are looking for?
Honestly, this code looks fine. However, from the error message, it seems that no successful response has been received.
I create a test web app with your code to get a token. My environment: .NET framework 4.7.2 and ADAL 5.2.7. The result is that I can successfully get a token.
So, you may try to update to use latest ADAL version and deploy you web application to a new web app.
If the problem still occurs, you may try to directly make a http request to get a token:
POST https://login.microsoftonline.com/{tenant-id}/oauth2/token
Content-Type: application/x-www-form-urlencoded
grant_type=password
&resource={resource}
&username={username}
&password={password}
&client_id={client-id}

Some windows container pods restarting on AKS & throwing RabbitMq connection failure from 60 pods and after several restarts come to running state

After deploying around 60 pods on AKS which uses Rebus RabbitMq. During the initialization, some around 15 pods restart several times and then come into running state. Below error thrown by the components,
*Unhandled Exception: Rebus.Injection.ResolutionException: Could not resolve Rebus.Bus.IBus with decorator depth 0 - registrations: Rebus.Injection.Injectionist+Handler ---> RabbitMQ.Client.Exceptions.BrokerUnreachableException: None of the specified endpoints were reachable ---> System.AggregateException: One or more errors occurred. ---> RabbitMQ.Client.Exceptions.ConnectFailureException: Connection failed ---> System.Net.Sockets.SocketException: No such host is known
at System.Net.Dns.HostResolutionEndHelper(IAsyncResult asyncResult)
at System.Net.Dns.EndGetHostAddresses(IAsyncResult asyncResult)
at System.Threading.Tasks.TaskFactory`1.FromAsyncCoreLogic(IAsyncResult iar, Func`2 endFunction, Action`1 endAction, Task`1 promise, Boolean requiresSynchronization)
--- 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 RabbitMQ.Client.TcpClientAdapter.<ConnectAsync>d__2.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 RabbitMQ.Client.Impl.TaskExtensions.<TimeoutAfter>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 RabbitMQ.Client.Impl.SocketFrameHandler.ConnectOrFail(ITcpClient socket, AmqpTcpEndpoint endpoint, Int32 timeout)
--- End of inner exception stack trace ---
at RabbitMQ.Client.Impl.SocketFrameHandler.ConnectUsingAddressFamily(AmqpTcpEndpoint endpoint, Func`2 socketFactory, Int32 timeout, AddressFamily family)
at RabbitMQ.Client.Impl.SocketFrameHandler..ctor(AmqpTcpEndpoint endpoint, Func`2 socketFactory, Int32 connectionTimeout, Int32 readTimeout, Int32 writeTimeout)
at RabbitMQ.Client.ConnectionFactory.CreateFrameHandler(AmqpTcpEndpoint endpoint)
at RabbitMQ.Client.EndpointResolverExtensions.SelectOne[T](IEndpointResolver resolver, Func`2 selector)
--- End of inner exception stack trace ---
at RabbitMQ.Client.EndpointResolverExtensions.SelectOne[T](IEndpointResolver resolver, Func`2 selector)
at RabbitMQ.Client.Framing.Impl.AutorecoveringConnection.Init(IEndpointResolver endpoints)
at RabbitMQ.Client.ConnectionFactory.CreateConnection(IEndpointResolver endpointResolver, String clientProvidedName)
--- End of inner exception stack trace ---
at RabbitMQ.Client.ConnectionFactory.CreateConnection(IEndpointResolver endpointResolver, String clientProvidedName)
at Rebus.Internals.ConnectionManager.GetConnection()
at Rebus.RabbitMq.RabbitMqTransport.CreateQueue(String address)
at Rebus.Config.RebusConfigurer.<>c__DisplayClass12_0.<Start>b__26(IResolutionContext c)
at Rebus.Injection.Injectionist.ResolutionContext.Get[TService]()
--- End of inner exception stack trace ---
at Rebus.Injection.Injectionist.ResolutionContext.Get[TService]()
at Rebus.Injection.Injectionist.Get[TService]()
at Rebus.Config.RebusConfigurer.Start()
at Castle.Windsor.Installer.AssemblyInstaller.Install(IWindsorContainer container, IConfigurationStore store)
at Castle.Windsor.WindsorContainer.Install(IWindsorInstaller[] installers, DefaultComponentInstaller scope)
at Castle.Windsor.WindsorContainer.Install(IWindsorInstaller[] installers)
at RebusHost.Main(String[] args)*
Although there is a connection available to RabbitMq server but some pods on start give this error and after 3 to 5 restarts they are in successful running state. So not sure what will be causing pod to not get connected on first attempt itself. Any clue will be appreciated.
We are using Rebus 4.0 & RabbitMq 5.1.0.0 versions. Deploying the components(pods) on windows node of AKS. And on AKS running docker image of "rabbitmq:3-management" under linux node ofcourse.

Authentication required (unexpectedly)

My vb.net code uses Mailkit to send emails via my ionos server.
Dim cl As New SmtpClient
cl.ServerCertificateValidationCallback = AddressOf AcceptAllCertifications
cl.Connect(email_host, 25, MailKit.Security.SecureSocketOptions.None)
cl.Send(de_mimemessage)
The code works fine normally but occasionally (perhaps once every few hundred times) I get the following error at the connect part of the code:
Authentication required
what can I do differently so that this error never occurs?
Here is the stacktrace...
(MimeMessage message, MailboxAddress mailbox, SmtpResponse response)
at MailKit.Net.Smtp.SmtpClient.<MailFromAsync>d__88.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at MailKit.Net.Smtp.SmtpClient.<SendAsync>d__99.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at MailKit.Net.Smtp.SmtpClient.Send(FormatOptions options, MimeMessage message, CancellationToken cancellationToken, ITransferProgress progress)
at MailKit.MailTransport.Send(MimeMessage message, CancellationToken cancellationToken, ITransferProgress progress)
at marketing_email_plus_removals.send_email(Boolean in_test, String in_email, String in_postcode) in E:\kunden\homepages\14\d650565413\www\marketing_email_plus_removals.aspx.vb:line 547
When you get an "Authentication Required" exception, it means that the server won't let you send that message until you authenticate.
When that happens, call:
cl.Authenticate ("username", "password");

New client not accepted

please could you help with following mysterious & interesting issue?
IIS websites:
IdentityServer (v 2.0.1) - used to login & get clientToken for service account (which is furhter used for IdentityServerApi calls)
IdentityServerApi - used to get user data from DB
WebSite1
WebSite2
WebSite3
WebSite4
NewWebapp
Startup.cs in IdentityServer contains Clients for all web sites
NewWebapp was added recently with exact same configuration as other websites (only ReturnUrl differs)
Classic (functional) scenario is:
WebApp gets clientToken from IdentityServer and this is used for all requests to IdentityServerApi (containing user & other data).
Current behavior is:
All WebSites1-4 work correctly. But when NewWebapp is trying to get clientToken it gets following error:
Exception:
System.Net.Http.HttpRequestException: An error occurred while sending the request. ---> System.Net.WebException: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel. ---> System.Security.Authentication.AuthenticationException: The remote certificate is invalid according to the validation procedure.
at System.Net.TlsStream.EndWrite(IAsyncResult asyncResult)
at System.Net.PooledStream.EndWrite(IAsyncResult asyncResult)
at System.Net.ConnectStream.WriteHeadersCallback(IAsyncResult ar)
--- End of inner exception stack trace ---
at System.Net.HttpWebRequest.EndGetResponse(IAsyncResult asyncResult)
at System.Net.Http.HttpClientHandler.GetResponseCallback(IAsyncResult ar)
--- End of inner exception stack trace ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter1.GetResult() at mySupply_project.Utils.RemoteUserApiProvider.<CallUserApi>d__7.MoveNext() in C:\tfs43\MySupply\MySupply-project-multilingual\mySupply-project\Utils\RemoteUserApiProvider.cs:line 91 InnerException: The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel. Message: Exception StackTrace: at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter1.GetResult()
at mySupply_project.Utils.RemoteUserApiProvider.d__7.MoveNext() in C:\tfs43\MySupply\MySupply-project-multilingual\mySupply-project\Utils\RemoteUserApiProvider.cs:line 91
TraceLog of IdentityServer does not contain any useful information.
When testing in Postman, requests are processed well, clientToken & data are correctly returned in all cases (including NewWebapp).
Please, does anyone have idea what could be possibly wrong?
Thanks a lot!
Update:
RemoteUserApiProvider calls this method:
public async Task<string> CallUserApi(string url)
{
var accesToken = ClientToken();
if (string.IsNullOrEmpty(accesToken))
return string.Empty;
try
{
using (var client = new HttpClient())
{
client.SetBearerToken(accesToken);
// turn off validation of a certificate for testing
CheckCertificationSettings();
_logger.LogInfo($"[CallUserApi] Url: {url}");
var result = await client.GetStringAsync(url);
return result;
}
}
catch (Exception ex)
{
_logger.LogException(ex, Source.IdentityServer);
return string.Empty;
}
}
This method CallUserApi calls url of IdentityServerApi (via https).
To get clientToken, IdentityServer (not Api) is called via https.
This doesn't seem to be identity related issue, what URL does the RemoteUserApiProbider call into? Check if the SSL of the URL is trusted on the same box as where the new client app is being hosted. You can use powershell or browser
Updated:
And try go through this checklist to see if any one of those is matched

get_Error_BPAAsimovNotReachedRetrying() not found when creating/validating cluster

I'm trying to create a standalone Service Fabric cluster using 5.4.145.9494 SDK bits and when running .\TestConfiguration.ps1 .\ClusterConfig.Unsecure.DevCluster.json with no changes to the downloaded SDK whatsoever I'm getting following error:
Test Config failed with exception: System.AggregateException: One or
more errors occurred. ---> System.MissingMethodExce ption: Method not
found: 'System.String
System.Fabric.Strings.StringResources.get_Error_BPAAsimovNotReachedRetrying()'.
at
Microsoft.ServiceFabric.DeploymentManager.Common.StandaloneSettingsValidator.Validate()
at
Microsoft.ServiceFabric.DeploymentManager.BPA.BestPracticesAnalyzer.IsJsonConfigModelValid(StandAloneInstallerJson
Model config) at
Microsoft.ServiceFabric.DeploymentManager.BPA.BestPracticesAnalyzer.AnalyzeClusterSetup(String
configPath, String cabPath, Boolean usingClusterManifest,
FabricPackageType fabricPackageType) at
System.Threading.Tasks.Task`1.InnerInvoke() at
System.Threading.Tasks.Task.Execute()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.ServiceFabric.DeploymentManager.BPA.BestPracticesAnalyzer.d__3.MoveNext()
--- End of inner exception stack trace --- at System.Threading.Tasks.Task`1.GetResultCore(Boolean
waitCompletionNotification) at
Microsoft.ServiceFabric.DeploymentManager.DeploymentManagerInternal.BpaAnalyzeClusterSetup(String
clusterConfigPat h, String fabricPackagePath) at
Microsoft.ServiceFabric.Powershell.ClusterCmdletBase.TestConfig(String
clusterConfigPath, String fabricPackagePath ) at
System.Management.Automation.CommandProcessor.ProcessRecord()
---> (Inner Exception #0) System.MissingMethodException: Method not found: 'System.String System.Fabric.Strings.StringRe
sources.get_Error_BPAAsimovNotReachedRetrying()'. at
Microsoft.ServiceFabric.DeploymentManager.Common.StandaloneSettingsValidator.Validate()
at
Microsoft.ServiceFabric.DeploymentManager.BPA.BestPracticesAnalyzer.IsJsonConfigModelValid(StandAloneInstallerJson
Model config) at
Microsoft.ServiceFabric.DeploymentManager.BPA.BestPracticesAnalyzer.AnalyzeClusterSetup(String
configPath, String cabPath, Boolean usingClusterManifest,
FabricPackageType fabricPackageType) at
System.Threading.Tasks.Task`1.InnerInvoke() at
System.Threading.Tasks.Task.Execute()
--- End of stack trace from previous location where exception was thrown --- at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task) at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task) at
Microsoft.ServiceFabric.DeploymentManager.BPA.BestPracticesAnalyzer.d__3.MoveNext()<---
The same error is printed when trying to use createservicefabriccluster.ps1.
I'm trying it on a Windows Server 2012R2 machine. Interestingly, the same works just fine on another Windows 10 machine. There are other differences (Windows Server 2012 R2 machine is in secure environment with a bunch of access policies around network, disk access, etc.) but it's hard to tell what's actually causing validation to fail with a message like that ...
My question: How do I get pass that "MissingMethodException" noise and learn the real issue?
Turns out that's the exception you get when the machine is already part of a previously defined standalone, non-Dev cluster. Running .\cleanFabric.ps1 made it work again.
Somebody should make the error message better ...