New client not accepted - identityserver3

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

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}

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 ...

Any idea why Facebook Provider fails in the below code?

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

Entity Framework 5 IBM DB2 EntityException The underlying provider failed on ConnectionString

I am using Visual Studio 2012 to build a web application. The application uses webforms, Entity Framework 5 with an IBM DB2 database server. I have the latest IBM Drivers v10.1.2 installed on both my development machine and my web server. The web server is running Windows Server 2008 R2 Standard x64bit OS.
Problem Im having is running the app under Visual Studio's IIS Express on my local machine works fine, however when I deployed the app the web server I am getting problems EF and DB2 Drivers. Here is the error and stack trace. What am doing wrong?!
Server Error in '/' Application.
--------------------------------------------------------------------------------
ERROR [] [IBM][CLI Driver] SQL0000W Statement processing was successful.
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: IBM.Data.DB2.DB2Exception: ERROR [] [IBM][CLI Driver] SQL0000W Statement processing was successful.
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:
[DB2Exception (0x80004005): ERROR [] [IBM][CLI Driver] SQL0000W Statement processing was successful.]
IBM.Data.DB2.ConnSettingsFromXmlConfig.ProcessFromXmlConfig(DB2Connection connection, String dbname, String host, String port, String tmpClientEncAlg, String tmpAuthentication, String prevdb, String prevdb_ori, DB2ConnSettings& sSettings, DB2ConnSettingsInternal& sSettingsInternal, StringBuilder& modifiedValue) +21370
IBM.Data.DB2.DB2ConnPool.ReplaceConnectionStringParms(DB2Connection connection, String szValue, DB2ConnSettings& pSettings, DB2ConnSettingsInternal& pSettingsInternal, Boolean bAttach, Boolean pushDownStrAppended) +19113
IBM.Data.DB2.DB2Connection.set_ConnectionString(String value) +187
System.Data.EntityClient.EntityConnection.ChangeConnectionString(String newConnectionString) +325
[EntityException: The underlying provider failed on ConnectionString.]
System.Data.EntityClient.EntityConnection.ChangeConnectionString(String newConnectionString) +391
System.Data.EntityClient.EntityConnection..ctor(String connectionString) +43
System.Data.Entity.Internal.LazyInternalConnection.InitializeFromConnectionStringSetting(ConnectionStringSettings appConfigConnection) +78
System.Data.Entity.Internal.LazyInternalConnection.TryInitializeFromAppConfig(String name, AppConfig config) +32
System.Data.Entity.Internal.LazyInternalConnection.Initialize() +127
System.Data.Entity.Internal.LazyInternalConnection.CreateObjectContextFromConnectionModel() +13
System.Data.Entity.Internal.LazyInternalContext.InitializeContext() +281
System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType) +18
System.Data.Entity.Internal.Linq.InternalSet`1.Initialize() +52
System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext() +15
System.Data.Entity.Infrastructure.DbQuery`1.System.Linq.IQueryable.get_Provider() +37
System.Linq.Queryable.Where(IQueryable`1 source, Expression`1 predicate) +63
....
I had the same problem and changing the app pool to Network Service did the trick.

Log4j Initialization error JBoss RestEasy

I am using JBoss 6.0. I am running a simple webserver using the jboss.resteasy library to provide simple XML responses to HTTP requests.
I have:
- A server
- A simple Java Client that creates a GET request
Now the thing is, if I use the browser to access the URL, I get the wanted XML. But if I use my Java client, which has the following code:
//Register the fake instrument
GetMethod get = new GetMethod("http:/localhost:8080/"+PROJECT_NAME+"/webserver/registerInstrument/?name=FakeClient&value=0");
HttpClient client = new HttpClient();
try {
int status = client.executeMethod(get);
} catch (HttpException e) {
System.out.println("[FakeClient] HttpException executing AddInstrument GET request: "+e);
} catch (IOException e) {
System.out.println("[FakeClient] IOException executing AddInstrument GET request: "+e);
}
Then I get the following exception:
log4j:WARN No appenders could be found for logger (org.apache.commons.httpclient.params.DefaultHttpParams).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" java.lang.IllegalArgumentException: Host name may not be null
at org.apache.commons.httpclient.HttpHost.<init>(HttpHost.java:68)
at org.apache.commons.httpclient.HttpHost.<init>(HttpHost.java:107)
at org.apache.commons.httpclient.HttpMethodBase.setURI(HttpMethodBase.java:280)
at org.apache.commons.httpclient.HttpMethodBase.<init>(HttpMethodBase.java:220)
at org.apache.commons.httpclient.methods.GetMethod.<init>(GetMethod.java:89)
at client.FakeClient.<init>(FakeClient.java:30)
at client.FakeClient.main(FakeClient.java:22)
At first I thought this could be a problem with the JBoss logging, but if I access the URL through the browser, I obtain the desired XML with no problems.
Is this a problem with the Java client application?
Thank you
The 'log4j:WARN' is just a warning. It has nothing do to with the actual exception being thrown.
The exception message states that 'Host name may not be null'. This clearly indicates that there is something wrong the the hostname. And looking at you code, I can spot one error.
You need to add an extra forward slash:
GetMethod get = new GetMethod("http://localhost:8080/" ...