400 status on login request for asp.net core 2.0 - jwt

I have the following issue.
After upgrading an application to ASP.NET 2.0 I get a 400 (bad request) status response whenever trying to authenticate in production.
This error does not reproduce locally and doesn't reproduce when using the production container locally.
The only difference that exists between production and local is that there is a reverse proxy in production that implements SSL for all requests.
I've tried moving the authentication code from middleware (as it was initially implemented) into a controller and I've changed the path to the route that was used for authentication. I still get the error.
All other requests work fine (provided you have a jwt token attached to them).
I should also mention that the CORS headers aren't set on the 400 response.
Any ideas?

This issue was caused by an upstream reverse proxy that was stripping some headers from the requests. Requests with verbs Post & Put were affected.
Set the log level of your application to Information to see what Kestrel is actually complaining about.
In our case we had to switch hosting providers because of the issue.

Related

IBM Weather REST API 401 Keep getting CORS issues when access

I am getting a 401 and some cross domain issues when trying to access IBM Weather REST API from either client (browser) or server.
If I generate a URL and try and access it directly from a browser (eg paste it in it works fine and the JSON weather report is returned).
When I try and run the Javascript HTTP request from either the browser or server it seems like it's only allowed to run from an ibm.com domain.
Failed to load https://twcservice.au-syd.mybluemix.net/api/weather/v1/geocode/-33.00/151.00/forecast/daily/7day.json?units=m&language=en-US: The 'Access-Control-Allow-Origin' header contains multiple values 'https://*.ibm.com, https://*.ibmcloud.com', but only one is allowed. Origin 'http://localhost:3000' is therefore not allowed access.
I am using the free service on Bluemix. Is this restricted to only run via a Bluemix server? or are there some options I can pass when I create the service on Bluemix
Note, when I make the request I am using the credentials supplied via the Bluemix console. Again, this works via the browser URL bar, but not via code.
Update/More info: if I hit past the URL above into the browser (with creds) it works as above, then if hit it via the web app in the same session it works.
Hmmm. So the IBM server is sending the following response header:
Access-Control-Allow-Origin: https://*.ibm.com, https://*.ibmcloud.com
That's an invalid response from IBM. Unfortunately, I think your only option is to complain to IBM, and convince them to
Return a valid Access-Control-Allow-Origin response header (with only one value)
Allow people outside of IBM to access it
Without that, I fear you're out of luck.

401 UnAuthorized - This request requires HTTP authentication - Payara/Glassfish

Initial Context:
We're developing Web Aplication Server and deploying it in Payara Server 4.1.2.173. The mininal stability testing are passing perfect and MVP works perfectly but in order to improve the performance testing of the system we have created different test case in JMeter (3.2) that simulates Front-End normal activity and make all the necessary requests to the server.
The problem:
When JMeter starts making request REST(JAX-RS) everything works fine but suddenly some requests (users) return the following error response:
<h1>HTTP Status 401 - Unauthorized</h1>
<hr/>
<p>
<b>type</b> Status report</p><p>
<b>message</b>Unauthorized</p><p>
<b>description</b>This request requires HTTP authentication.</p>
<hr/>
It's very strange because the error appears randomly and apparently it is not because of concurrency problems.
Any ideas what might be the issue? Thanks
After a few research I've discovered that JMeter has some difficulties to add dynamic header token to Http request when volume Thread request are increasing. In my scenario I was doing the following:
Making a HTTP Login request
Generating token session in Server
JMeter gives the token from the response and I apply post-processor to encode it to Base64 and save to JMeter system variables.
In the next HTTP request I add the token in HTTP Header configuration component as a Basic Authorization.
When the amount of Threads increase (150 approx) Server return error 401. Despite of JMeter shows as if the token are included in header, there is no sign of it in the real request. The behaviour appears randomly and with no common reason...
Solution:
We have decided to add token session as a part of CSV Data set - configuration file and JMeter is capable of manage all requests without any rare 401 error.

Apache Camel HTTPS4 Basic Authentication

Does Camel-Http4 supports Basic Authentication?
Followed this and other posts
Camel http4 download file using Basic authentication over Https
I am using camel 2.17.3 version. using camel-http4 component. The route sends a https4 multipart request to a REST endpoint . The REST service is behind the siteminder. Have truststore/ketstore/cert all setup and it works fine, just sending basic auth is causing trouble.
Using postman i was able to call REST services with basic auth. However, all the calls from camel route fails and get HTTP error 403.
I tried below options to get it working:
Added basic auth to the HttpConfiguration - got HTTP error 401
Added "Authorization" header to the route, as mentioned in the above link - got HTTP error 403
and Added method,user,pass to HTTP_Query - 403 also clear text password is visible in the siteminder logs, this is not good, so dropped trying this option.
please help resolve this issue with some working example and explain the cause.
Is camel dropping http headers?
also i now thinking should I consider using other available components netty/jetty/cxf?? But I prefer getting HTTPs4 working :)
thanks
To help others with an working example, here is how I got it...
1) Check the site-minder policy and also ensure the user have correct permissions for the services.
2) Passing user/password as query parameter isn't safe (at least it wasn't in my case) Clear text password was exposed in site-minder.
3) setting header (Authorization)
apache-camel-basic-http-auth

Authenticating in Azure but calling web api on localhost - 401

I have an Azure mobile app authenticating on azure with FB and Twitter. I am able to login to both but when testing web api calls locally (hosted in IIS) - any controller with the Authorize attribute - returns a 401.
The alternateLoginHost is set to the Azure host and it is providing me with a token after a successful login.
I followed the instructions in the docs about setting up Local debugging with authentication.
It is using attribute based routing - config.MapHttpAttributeRoutes()
Here is my full OWIN startup class
public class OwinStartup
{
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
new MobileAppConfiguration()
.ApplyTo(config);
app.UseAppServiceAuthentication(new AppServiceAuthenticationOptions()
{
SigningKey = ConfigurationManager.AppSettings["authSigningKey"],
ValidAudiences = new[] { ConfigurationManager.AppSettings["authAudience"] },
ValidIssuers = new[] { ConfigurationManager.AppSettings["authIssuer"] },
TokenHandler = config.GetAppServiceTokenHandler()
});
app.UseWebApi(config);
}
I have seen references in the documentation about either using the global http config passed in from asp.net or creating a new one - I tried referencing the GlobalConfiguration.Configuration instead of creating a new instance but it didn't help.
Is there a way to hook into the OWIN pipeline to see if the token is making it to the app service authentication module?
[EDIT] ZUMO AUTH HEADER
I am also adding the x-zumo-auth header and setting it's value to the token from the current user like this
request.headers.append('X-ZUMO-AUTH',
app.azureClient.currentUser.mobileServiceAuthenticationToken)
And I can see it in each request being made to the api. A call to the endpoint https://mysite.azurewebsites.net/.auth/me using this mechanism is returning a correct response so I know the token is valid.
[EDIT] Verified working in Azure after adding ZUMO Version Header
deployed the web api to azure and tried to call my web api endpoint and received a bad request error. It turns out it required an additional header for the version
'ZUMO-API-VERSION', '2.0.0'
I added the header and it worked.
Tried the local call again with the version header but still getting 401.
All I can assume is the OWIN middleware is not receiving the token probably due to a config problem - need some transparency into the pipeline to test some of these theories - not sure the best way to do that
Not sure where to look next in solving this.
[EDIT] OWIN Pipeline Authenticate stage Hook
OK - figured how to set up the equivalent to asp.net pipeline event handlers in OWIN - in my startup file I added this code to execute when the Authenticate stage is reached
app.Use((context, next) =>
{
return next.Invoke();
});
app.UseStageMarker(PipelineStage.Authenticate);
Added a breakpoint and when the debugger stops I can see that in the call stack
that the Azure App Service Middleware in in the pipeline
Microsoft.Owin.Security.Infrastructure.AuthenticationMiddleware
<Microsoft.Azure.Mobile.Server.Authentication.AppServiceAuthenticationOptions>
.Invoke(Microsoft.Owin.IOwinContext context)
Confirmed OWINContext.Request.Headers Contains the Correct Auth Token
Looking in the debugger the token is indeed in the Context.Request.Headers collection at the Authenticate stage of the OWIN pipeline and it has the correct value. For some reason still receiving the 401 status
I doubly checked the value I am using for the SigningKey - copied from the WEBSITE_AUTH_SIGNING_KEY value in Azure.
[EDIT] Debugging with source and exception being thrown in ValidateIdentity
AppServiceAuthenticationHandler.ValidateIdentity
Downloaded source v1.1.157.1, loaded symbols from symbolsource but those are marked as 1.0.157.1 and visual studio is complaining that the source is different than when the module was built. Because of this I cannot step through the code to see the exception that is being caught.
[EDIT]Built and Referenced v1.1.157.1 DLL - exception type now visible
In the ValidateIdentity method when it calls
options.TokenHandler.TryValidateLoginToken
The following exception is thrown
"Could not load type 'System.IdentityModel.Tokens.JwtSecurityToken'
from assembly 'System.IdentityModel.Tokens.Jwt, Version=5.0.0.127,
Culture=neutral, PublicKeyToken=31bf3856ad364e35'."
[EDIT] Finally found and fixed the issue
There was an issue posted on GitHub for IdentityServer having to do with a breaking change with a nuget package - going from v4 -> v5 of System.IdentityModel.TokensJwt package.
https://github.com/IdentityServer/IdentityServer3/issues/3017
I downgraded my install to v4.0.x and it fixed the exception and also fixed the 401 errors I was seeing when running locally.
All is good now
Do you have the correct app settings for authSigningKey, authAudience, and authIssuer in your web.config?
FYI -- a good writeup of the setup is here in case you haven't stumbled upon it yet: http://www.systemsabuse.com/2015/12/04/local-debugging-with-user-authentication-of-an-azure-mobile-app-service/
Is your localhost serving https traffic?
If a controller is decorated with [Authorize] it will require that the request/response occurs over https.
If you're targeting http://localhost, [Authorize] will cause a 302 to https://localhost.
This 302 can break the auth process. The solution would be to serve https locally, point your client to the appropriate port (my box uses :44300), and try it out again.
Also, make sure any relevant redirect URLs go to the https:// version of the URLs you're using.

Issue Testing after IdentityServer3 Deploy

After going through walkthroughs I had a test mvc app, test web api, and identityserver3 all working perfectly on my machine. I deployed IdentityServer3 to our servers in AWS behind a load balancer. I followed all the instructions in the Deployment wiki. I am able to hit the .wellknown configuration fine after deployment from a browser on my machine.
I changed the authority url for the mvc and api test apps to point to the aws deployment. Clients, Scopes, users, etc are all configured identically as they are hitting the same database as it was when running on local machine.
I can get an access token using RequestResourceOwnerPasswordAsync just fine so I think ids is installed fine.
However, both the API and the MVC app just trying to use implicit flow are now failing. FOr instance, when I try to hit a mvc controller action marked with [Authorize] I get an error stating "An invalid request URI was provided. The request URI must either be an absolute URI or BaseAddress must be set".
If I try to hit the webapi from the mvc app (both running locally on my machine) after a successful RequestResourceOwnerPasswordAsync call, I get the error "Response status code does not indicate success: 401 (Unauthorized)." after what seems like a timeout.
Any help would be greatly appreciated.
Figured out the problem. When specifying PublicOrigin, it has to be a full URL and not just the domain. I had left off https:// prefix.
The web api issue was related to connectivity to the identity server. There was some incorrect proxy settings for the app.