IdentityServer4 override BadRequest for invalid_client - identityserver4

We have a basic IdentityServer implementation using ClientCredentials. When a token is requested with an invalid secret, we're receiving an invalid_client error with a 400 BadRequest status. What is the best way to override this response and return a 401 unauthorized? We have a remote device accessing our api which expects a 401 for authentication errors.

One option is to work with another project that works as a facade in the middle, connects to the /connect/token methods and then gives a different response having 401. Here are some links:
https://microservices.io/patterns/apigateway.html
How to setup a Web API Facade pattern

Related

IdentityServer API unauthorized if hosted in IIS

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.

OPTIONS Error using twitter API (400)

For my personal website, I'd like to create a page summarizing my social presence.
I used Postman to make sure all my queries are valid.
So I made simple call to get my last post on twitter.
Everything works find on Postman, so there isn't any Authorization issues.
But when it comes to implement it on my client (using AngularJs ), I'm getting this error:
OPTIONS https://api.twitter.com/1.1/statuses/user_timeline.json?user_id=1106474965 400 ()
XMLHttpRequest cannot load https://api.twitter.com/1.1/statuses/user_timeline.json?user_id=1106474965. Response for preflight has invalid HTTP status code 400
I know it may be related to How does Access-Control-Allow-Origin header work? but I can't configure the server as I subscribed a shared hosting
(One.com).
I tried to reset my $httpProvider default values in vein.
It seems Twitter API doesn't support CORS headers, and that's why your preflight tests are failing:
https://twittercommunity.com/t/will-twitter-api-support-cors-headers-soon/28276

Trying to use Converged Microsoft Account and Azure AD with mod_auth_openidc

After reading the following article:
http://blogs.technet.com/b/ad/archive/2015/08/12/azure-ad-microsoft-account-preview-sign-in-personal-and-work-accounts-using-a-single-stack.aspx
I tried to implement an OpenID Connect/Oauth code flow per the documentation at:
https://azure.microsoft.com/en-us/documentation/articles/active-directory-appmodel-v2-overview/
I'm using mod_auth_openidc as my Relying Party (that I have working with both Google and my own OpenID Provider.
I've registered my app at https://apps.dev.microsoft.com, and gone through all the steps. I get the login screen at microsoft, then the permissions screen and when it redirects back to my site and hits mod_auth_openidc, I get an error that says:
Error:
The OpenID Connect Provider returned an error: Error in handling response type.
In my Apache Error logs I get:
oidc_proto_validate_code_response: requested flow is "code" but no "access_token" parameter found in the code response, referer: https://login.microsoftonline.com/common/oauth2/v2.0/authorize?response_type=code&scope=openid&client_id=xxx&state=yyy&redirect_uri=https%3A%2F%2Fdst-dev.mydomain.com%2Foauth2callback&nonce=zzz
and
oidc_proto_resolve_code_and_validate_response: code response validation failed,
What I'm trying to figure out is where the problem lies. Is there an issue with what Microsoft is sending mod_auth_openidc, or is there a bug or configuration issue on the mod_auth_openidc side?
The example at MS webpages uses a different response mode and response type in the authentication request:
&response_mode=form_post&response_type=code+id_token
both are supported by mod_auth_openidc so you could apply something similar by including:
OIDCResponseType id_token
OIDCResponseMode form_post
in the Apache configuration or using the associated primitives in the .conf file for Microsoft when using multiple providers.

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

Connection Refused using access token from OAuth 2.0 User-Agent Authentication from Salesforce

I'm using OAuth2.0 User-Agent Authentication flow to get the access & refresh tokens so that I can use the Foce.com REST API over remote access. Now, the problem is that I'm able to authorize successfully and recieve the tokens, but while using those tokens just after authorizing my client application, I'm recieving a java.net.ConnectException: Connection refused error.
Following Steps I'm doing
Redirecting to
https://login.salesforce.com/services/oauth2/authorize?response_type=token&client_id={my_client_id}&redirect_uri={my_redirect_uri}&state=myState
Authorizing the app in salesforce and then receiving back the access token and refresh tokens in the hash of the redirect_uri as
{my_redirect_uri}#access_token={my_access_token}&refresh_token={my_refresh_token}&instance_url=https%3A%2F%2Fap1.salesforce.com&id=https%3A%2F%2Flogin.salesforce.com%2Fid%2F00D90000000gscOEAQ%2F00590000000sdtJAAQ&issued_at=1351151192815&signature={my_signature_value}&state=myState
&scope=id+api+refresh_token
Now I'm using the REST API using the same access token by doing a POST to
https://ap1.salesforce.com/services/data/v20.0/sobjects/Lead/
with request headers:
Content-Type: application/json
Authorization: OAuth {my_access_token}
I have not escaped the access token while sending the post as it needs to be done when using CURL. Is that needed when using HttpClient Java API also?
The response that I'm getting is "java.net.ConnectException: Connection refused error."
Can someone please let me know what I'm doing wrong or how I can debug it further ?? Is there any way to see whats happening at Salesforce end? Some logs may be ?
I'm getting the exact same connection refused error if I try OAuth Refresh Token Process also.
Sorry for the noise.
I was getting "invalid_grant" with "expired access/refresh token" while validating the customer secret using the Refresh Token Procedure but since it was secured transmission so all I was getting in Java was "Connection Refused" with no detailed error message.
I got to know the detailed error by Setting up SSL Proxy in Charles as described here. After that I was able to see the request parameters and response send to https://ap1.salesforce.com which was earlier not readable.

Resources