IdentityServer API unauthorized if hosted in IIS - identityserver4

I added additional API to the Duende IdentityServer 6.2 as described here. Then I tried to access it from a sample App, using typed httpClient using their own library called AccessTokenManagement (aka Identity.Model) pretty much following their simple example. I use Authorization Code flow, everything pretty much simple and default.
It works well until both server and client are on the same dev machine under localhost. As soon as I publish IdentityServer to IIS, the API stops to work, while the rest still works well (I can be authenticated, and I see in the Fiddler that token exchanges work normally).
The call to API consists from two calls:
Calling to /connect/token using refresh token. Server returns access token.
Calling my endpoint using this new access token.
The flow fails on the step 1. Call to /connect/token is already unauthorized and I can't understand why. The "good" and "bad" calls looks the same, I cannot see any differences. Previous call moment ago to /connect/userinfo consists of the same two steps and it works. Logs on both server and client give no clues.
No reverse proxies, just good plain simple URI. Automatic key management is enabled and the keys are in the SQL table, common for dev and published server. Asp.Net Core Data Protection is enabled and keys are also common.
Relevant parts of logs are below. I noticed that "No endpoint entry found for request path" is specific to IdentityServer and it doesn't actually mean that endpoint was not found. It was found but not processed. I also noticed reacher response headers from bad request and log entry about "Cookie signed-in" in good request but not sure what does it mean and whether it's relevant.
I'm running out of ideas.
Bad response from IIS while trying to get new Access Token:
Proper response while developing:
///////Relevant part of log for BAD request
|Duende.AccessTokenManagement.OpenIdConnect.UserAccessAccessTokenManagementService|Token for user test#test.com needs refreshing.
|Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler|AuthenticationScheme: cookie was successfully authenticated.
|Duende.AccessTokenManagement.OpenIdConnect.UserTokenEndpointService|refresh token request to: https://auth.mysite.org/connect/token
|Duende.AccessTokenManagement.OpenIdConnect.UserAccessAccessTokenManagementService|Error refreshing access token. Error = Unauthorized
|System.Net.Http.HttpClient.IdsService.ClientHandler|Sending HTTP request POST https://auth.mysite.org/mycontroller/myaction
|System.Net.Http.HttpClient.IdsService.ClientHandler|Received HTTP response headers after 117.7278ms - 401
///////Same part of GOOD request
|Duende.AccessTokenManagement.OpenIdConnect.UserAccessAccessTokenManagementService|Token for user test#test.com needs refreshing.
|Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler|AuthenticationScheme: Cookies was successfully authenticated.
|Duende.AccessTokenManagement.OpenIdConnect.UserTokenEndpointService|refresh token request to: https://localhost:5001/connect/token
|Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler|AuthenticationScheme: Cookies signed in.
|System.Net.Http.HttpClient.IdsService.ClientHandler|Sending HTTP request POST https://localhost:5001/mycontroller/myaction
|System.Net.Http.HttpClient.IdsService.ClientHandler|Received HTTP response headers after 1994.9611ms - 200
///////Server log during BAD request
Duende.IdentityServer.Hosting.EndpointRouter No endpoint entry found for request path: "/mycontroller/myaction"
Duende.IdentityServer.Hosting.LocalApiAuthentication.LocalApiAuthenticationHandler HandleAuthenticateAsync called
Duende.IdentityServer.Hosting.LocalApiAuthentication.LocalApiAuthenticationHandler AuthenticationScheme: "IdentityServerAccessToken" was not authenticated.
Duende.IdentityServer.Hosting.LocalApiAuthentication.LocalApiAuthenticationHandler AuthenticationScheme: "IdentityServerAccessToken" was challenged.

Okay, found it. Thankfully, looked at Fiddler's WebView and had seen familiar picture!
Then, found this topic. The solution was disabling Basic authentication in IIS settings. Access token request has basic authentication header and it seems like IIS intercepts it. Still a bit unclear why other parts of flow worked.

Related

Amazon SP API getting internal server error

I am trying to get access token from api https://api.amazon.com/auth/o2/token
POST /auth/o2/token HTTP/l.l
Host: api.amazon.com
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
grant_type=refresh_token
&refresh_token=Aztr|...
&client_id=foodev
&client_secret=Y76SDl2F
But after POST request I get 500 server error.
Is it because my app is in draft status? or I am missing something while making request?
If it because of draft status then when the status will get change? any thoughts on this.
Thank you for your help in advance.
The documentation is wrong. I was getting the same exact error and came across this comment on a github issue which mentioned that the data has to be passed into the body of the request, not as query string parameters. Sure enough, this worked for me and I was able to get an access token. So just to clarify: grant_type, refresh_token, client_id, and client_secret should be passed into the body of the POST request to https://api.amazon.com/auth/o2/token and NOT as query string parameters.
Draft status will not keep you from requesting and receiving the access token.
Here are a few things to check as not much can be derived from the example post request from the documentation:
Did you configure AWS IAM role / policy / user properly
Did you use the correct IAM ARN when registering the application
Are you using the correct LWA credentials (I am assuming you're not passing foodev and Y76SDl2F as those are example parameters)
Have you self authorized the application (are you using the refresh token generated
for the authorized application)
Are you 'assuming the role' before the token exchange -- this is a very important step
and is very different in comparison to how access was handled with MWS -- if
you have not, the server will reject the token exchange regardless if the refresh
token is correct. More on that here
This is a non-exhaustive list, just some common issues I have seen other developers have with getting the access token during development, if these don't work you'll need to work with support as they can see the requests hitting the token endpoint.

(NodeJS / AngularJS) POST request with 'x-auth' token to server, but token seems to get lost in preflight (no error though)

Background
I have a simple NodeJS server hosted on localhost/Heroku which handles JWT authentication for adding data to the registered user amongst other (unrelated) things.
Here's the GitHub: https://github.com/mlee93dev/pw-keychain-server
I also have a simple Angular2 client on localhost/Heroku for this server:
https://github.com/mlee93dev/pw-keychain-app
Currently, I have my JWT access tokens configured to last only 5 seconds in my server for development purposes.
I have my CORS stuff configured to the best of my knowledge as shown below in server.js:
CORS configuration pic
The Problem
On Postman I test the POST request and I get the expected response - a JWT expiration error:
Postman POST pic
However I don't get the same response on my client - rather, I get a 'JWT must be provided' error:
Client POST pic
As you can see in the pic above, I know I'm actually attaching a token as I console.log it. Here's a pic of the code:
Client POST code pic
So what's confusing me more is that my DELETE request (for logging out) also implements the same x-auth token to request code, and it works in both Postman + client, as seen here:
DELETE error response
DELETE code
So yeah, I'm pretty confused. My guess is I have to configure my CORS some more to allow x-auth header on POST requests specifically somehow? Even though I think it should do that already with my current configuration.
You are providing the body in post request instead of headers.
Angular POST request
So in your post request just do the following
this.http.post(yoururl, {},{headers:new Headers({'x-auth':token})})...
And it should work.

How to use SAML authentication in a mobile application?

I'm trying to understand how an saml authentication flow could work in a mobile environment where the client (AngularJS based), api server (Node & passport based), and idp exist on different domains.
From what I've gathered the general practice is to have the server return a 401 to the client if there's no authentication present (i.e. the client didn't include a bearer token in the request). The client understands that a 401 response indicates to open up the login endpoint on the server. When the login endpoint is opened it makes a passport call to the auth provider (which redirects the user to the auth provider's site) and supplies a callback URL. When the user authenticates, the auth provider redirects to the provided callback URL, which allows the server to retrieve information from the auth provider's response and construct a token of some sort (e.g. JWT) that can be used by the client (i.e. included in the headers) when making REST calls to identify itself.
My question is: How does the client get the token from the server? Because we're in a redirect-based authentication flow, I can't just return token from the callback function; that would just display the token in the browser without handing it off of to the client. Does the server just issue a 302 redirect pointing back to the client domain and include the authentication token in a header? Maybe I should not redirect from the client to the server in the first place and instead window.open() and use window.opener.postMessage or is that too old fashioned/mobile-unfriendly?
This question talks about authentication against a SAML IDP, but I'm interested in getting more details specifically about that last bullet point and how it would work with an AngularJS-based client.
Many examples I've seen online are either a single domain using OAuth/SAML (passport-saml-example), which avoids the issue of having the client exist on a separate domain, or use two domains with basic authentication, which avoids the issue of redirecting to some third party for authentication, but I'm having trouble finding good examples that uses all the bits and pieces I'm trying to work with.
This blog post seems very close to what I'm trying to accomplish (see googleSignInCallback) and uses a 302 redirect like I imagined but that solution relies on explicitly knowing the client URL to redirect to, which seems like it could be problematic if I wanted to support multiple client types (i.e. Native applications) in the future.
Eventually I was able to work together a solution by having my application open a browser window (Cordova's InAppBrowser) to a SAML-enabled application, have that application complete the normal SAML flow, and then that SAML-enabled application generated a JWT. My mobile application was then able to extract the JWT string from the browser window with the InAppBrowser's executeScript functionality. Then I could pass that JWT string along to my API server, which was able to validate the JWT is properly signed and trusted.
After I implemented my solution I saw that there was similar functionality available on github:
https://github.com/feedhenry-templates/saml-service
https://github.com/feedhenry-templates/saml-cloud-app
https://github.com/feedhenry-templates/saml-cordova-app
Hopefully this helps anyone else trying to deal with this issue!

IE11 overrides Bearer authorization header in intranet environment

I'm encountering a pretty strange issue in IE11 where the browser is overriding the Authorization header in my requests even though I am setting it via AngularJS.
Basically, I have an HTTP interceptor registered for all requests that looks like this:
AuthInterceptorService.request = function (config) {
config.headers.Authorization = "Bearer " + bearerToken;
}
This works great in all browsers (even IE under certain conditions). I have my app set up in IIS as allowing anonymous authentication and I have basic/integrated authentication disabled for this subsite, however, the parent configuration has windows authentication eabled.
What is happening occasionally is that the browser will make a request to the root URL for a static file (say, /favicon.ico). This request is denied with a 401. The browser responds with negotiated authentication and gets the favicon. At this point, all other browsers still let my code set the Authorization header, but once this integrated authentication happens in IE, the authorization header seems to get stuck - no matter what my code does, the authorization header is always using integrated authentication. This causes all requests to my API to fail because no Bearer token is present.
I was able to work around the favicon issue by specifying a more local favicon (where static files can be served anonymously), but I am wondering if there is a less hacky solution to this issue. Can I somehow convince IE to let me set the Authorization header even if Windows authentication has taken place on a previous request?
Note: I found this question which seems to be related (maybe the same underlying cause).
If you look at the Negotiate Operation Example of the RFC 4559 document, it involves a pseudo mechanism used by IE to negotiate the choice of security when authenticating with IIS.
The first time the client requests the document, no Authorization
header is sent, so the server responds with
S: HTTP/1.1 401 Unauthorized
S: WWW-Authenticate: Negotiate
The client will obtain the user credentials using the SPNEGO GSSAPI
mechanism type to identify generate a GSSAPI message to be sent to
the server with a new request, including the following Authorization
header:
C: GET dir/index.html
C: Authorization: Negotiate a87421000492aa874209af8bc028
The server will decode the gssapi-data and pass this to the SPNEGO
GSSAPI mechanism in the gss_accept_security_context function. If the
context is not complete, the server will respond with a 401 status
code with a WWW-Authenticate header containing the gssapi-data.
S: HTTP/1.1 401 Unauthorized
S: WWW-Authenticate: Negotiate 749efa7b23409c20b92356
The client will decode the gssapi-data, pass this into
Gss_Init_security_context, and return the new gssapi-data to the
server.
So, I don't think its possible for you to intermingle while the negotiation takes place as the process is internal

Salesforce returning "unsupported_grant_type"

We implemented OAuth 2.0 using Web Server Authentication Flow. It was working fine in October/November but all of a sudden it has stopped working. Whenever we try authorising another client the server return (400) Bad Request with the body
{"error":"unsupported_grant_type","error_description":"grant type not supported"}
grant_type is set as authorization_code which is definitely valid.
Is there any reason why OAuth would suddenly stop working?
This is how we have implemented OAuth:
First user is directed to: https://login.salesforce.com/services/oauth2/authorize?response_type=code&client_id=blah.id&redirect_uri=https://domain.com/Web/Salesforce/Callback.aspx&scope=api%20refresh_token
User is prompted by Salesforce to login to their account.
Once user is authenticated Salesforce calls Callback.aspx, Callback.aspx requests refresh token on behalf of the client by making a POST request to: https://login.salesforce.com/services/oauth2/token with the payload:
grant_type=authorization_code&code=blah.code&client_id=blah.Id&client_secret=11111111&redirect_uri=https://domain.com/Web/Salesforce/Callback.aspx
Content type is definitely: application/x-www-form-urlencoded
After lot of fiddling around with fiddler figured out there was a space before grant_type=authorization_code in HTTP POST payload that was causing the issue.
Interestingly that space has been there in code base since July and this issue was first noticed on 14th Jan. It is possible Salesforce fixed a bug or made an internal change to reject space before grant_type=authorization_code.
Make sure you are using 'https' not http
If you are having this error while authorising an Org through terminal sfdx command -
error authenticating with auth code due to: grant type not supported
Worked for me 'https' solved my grant type not supported problem.

Resources