ERR_INSECURE_RESPONSE - https

In my angular2 app I making a HTTPS post request to the API:
this.http.post('https://myhost.com/api/users/sign_in', body, { headers: contentHeaders })
.subscribe(
response => {.....
And I am getting "failed to load resource: net::ERR_INSECURE_RESPONSE"
Everything was fine with HTTP until I switched to HTTPS.
I am using self signed certificate for myhost.com.
In browser I am able to accept the certificate and make a request to the API. Could I resolve this also to make an API request via http.post from angular2 directly?

Related

Youtube Data Api Search Endpoint 401 Error

I'm trying to use the Youtube search endpoint, which does not seem to require an OAuth token. I've read a few tutorials and they only pass an API key. I'm getting a "Failed to load resource: the server responded with a status of 401 ()" error in my console in Chrome Dev Tools. Specifically, looking at the Network tab I get this:
I notice it says that there is an error: "invalid_token" but I pass the api key so they must be talking about the OAuth token? I'm confused because it shouldn't need one, especially because I'm just doing a query for public data. Even the Try This API portion of the endpoint documentation does not need one. Most importantly, my call in Postman works and just pasting the endpoint in my browser directly works. Why doesn't it work? This is using an axios call from a ReactJS frontend.
const apiKey = 'MY_API_KEY';
const url = 'https://www.googleapis.com/youtube/v3/search';
const response = await axios.get(url, {
params: {
part: 'snippet',
maxResults: 5,
q: songName,
key: apiKey
}
});
What was happening was that I was using axios.defaults.headers.common['Authorization'] =Bearer ${params.access_token}; in other calls for another API. This causes default everything to have this access token! So what I did for now is delete axios.defaults.headers.common["Authorization"]; -- the solution is pretty obvious, just make sure you have no extra headers because Search is not a OAuth endpoint!

CORS policy error with AWS API Gateway in React

I am trying to set up an API Gateway to call another lambda function that will upload an image to S3. The feature works well when I am using an app like POSTMAN, however when I run the browser using React I am getting the following error.
Access to fetch at 'https://.../upload' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
In my API Gateway I have the following configuration for that method
Gateway Responses for UserUpload API: default 4XX (not checked), default 5XX (not checked)
Methods: post (checked), options (checked)
Access-Control-Allow-Methods: options, post
Access-Control-Allow-Headers: '*'
Access-Control-Allow-Origin: '*'
This API uses an authorizer, I am using the one provided by Auth0 and have not edited the code at all.
And the function that my authorizer calls returns the response like the below (eg happy path):
exports.handler = async (event) => {
//do data checks and upload to s3
return {
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Methods": "*",
"Access-Control-Allow-Origin": "*",
},
statusCode: 200,
body: JSON.stringify({ message: "success" }),
};
This is my first time setting up both a lambda function, authorisation provider and API Gateway so I might be missing something obvious. I have also tried added mode: no-cors to my fetch POST requests however they still fail in a very similar way.
From what I can tell by looking at the logs of the authorizer and the lambda function that uploads the images, is that they are not even being called. So it appears the CORS error is with the API Gateway.
I have seen in a few tutorials that in their aws template yaml files they add an option AddDefaultAuthorizerToCorsPreflight as False. I can't see this anywhere in the API Gateway console.
Update: I have tested my function with the custom authoriser turned off and it works. So I know that CORS works for the options method, and for the returned request on the lambda function. It is the custom authoriser that is the problem.
The flow is currently:
Method Request - Auth: my-auth-0-authorizer
Integration Request - Type: Lambda_proxy
Lambda function
Integration response - [greyed out Proxy integrations cannot be configured to transform responses]
Method Response: HTTP Status: Proxy (with Access-Control-Allow-Origin in the response headers)
What do I have to do differently or change to allow my authoriser to respect the CORS config?
Update: After leaving my API Gateway for a day, successful responses are now working (using the flow mentioned above). I am not sure if there was a glitch in the system or there was unexpected occurring but it is now working. I am still getting a CORS issue but now only with bad responses.
The custom authoriser fails by return context.fail("Unauthorized"); and when this occurs my browser gets a CORS error. Do I have to set up special gateway responses for 4XX responses?

SignalR connection failing when calling through an intermittent WebApi Service

I've an angular app, a gateway service(web api) and an asp.net core service(where the SignalR hub is present). I'm trying to connect from the angular app to SignalR hub through the gateway and the request is failing with the below error:
Access to XMLHttpRequest at '(gateway)/signalR/connect/negotiate' from origin '(UI website)' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
//UI code:
this is request I'm posting from angular app.
const connection = new signalR.HubConnectionBuilder()
.withUrl(https://gateway/signalr/connect)
.withAutomaticReconnect()
.build();
//Gateway code:
https://gateway/signalr/connect is a post api in gateway service.
With in the gateway post api, I'm making a connection to signalr hub like below:
https://localhost:19081/(myservice)/SignalR/(myHub)
//SignalR Service:
Also added the below cors policy in my signalr startup:
services.AddCors(options => options.AddPolicy("SignalRPolicy", builder =>
{
builder.AllowAnyHeader()
.AllowCredentials()
.AllowAnyMethod()
.WithOrigins(<allowedorigins>);
}));
app.UseCors("SignalRPolicy");
app.UseAzureSignalR(routes =>
{
routes.MapHub<HubClass>("/<myhub>");
});
If I directly call the SignalR hub from UI - this request is passing and connecting to signalr successfully.
Here both Gateway service and my signalr service are hosted on azure service fabric. The requirement is, all the calls from UI need to go through the gateway.
Please let me know how I can make this work. Thank you.
You must to explicit (withCredentials: false) at hub connection.
const connection = new signalR.HubConnectionBuilder()
.withUrl(https://gateway/signalr/connect,
{ skipNegotiation: false,
withCredentials: false,
transport: signalR.HttpTransportType.WebSockets })
.withAutomaticReconnect()
.build();

Cross-Domain Ajax Requests WSO2 IS

curl -v -X POST -H "Authorization: Basic <base64 encoded client id:client secret value>" -k -d "grant_type=password&username=<username>&password=<password>" -H "Content-Type:application/x-www-form-urlencoded" https://localhost:9443/oauth2/token
(from https://docs.wso2.com/display/IS520/Resource+Owner+Password+Credentials+Grant
)
This 'curl' command works perfectly. But when try to call it through ajax:
$.ajax({
type: 'POST',
data: 'grant_type=password&username=admin&password=admin',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic Z0hLUlA3eThYTmJydl9JR1pJemxDQ1VJQlo0YTozT2VLaUlmUVViMk1yZzZ2YU5uQVFsWFpDU29h'
},
url: 'https://localhost:9443/oauth2/token',
success: function(data) {
console.log(data);
}
})
};
I got this error: "XMLHttpRequest cannot load https://localhost:9443/oauth2/token. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access."
How can I configure WSO2 IS to deal with it? Or is there an alternetive for this?
There is a similar issue with WSO2 API Manager (WSO2 API Manager CORS). But there is no such directory '/repository/deployment/server/synapse-configs/' in WSO2 IS.
This is the expected behaviour when cross origin resource sharing (CORS) is not enabled on Identity Server. In fact you can enable CORS for Identity Server. Check [1] on how to do it.
[1] http://hasanthipurnima.blogspot.com/2016/05/applying-cors-filter-to-wso2-identity.html
I don't think the Token API of IS returns CORS headers. To get this working, you can front Token API of IS by API Manager. By default, APIM returns CORS headers in all REST APIs you create in it.
In fact, API Manager ships an API (i.e. https://localhost:8243/token) which fronts the token API of IS (i.e. https://localhost:9443/oauth2/token) (note: APIM has certain IS features installed in it). But it does not return CORS headers too. To make it return CORS headers, you should follow that SO link you have mentioned.
Another simple option is, if you only need CORS headers, you can simply front Token API of IS by another custom services which returns CORS headers in the response.

Clicking an href to our Github oAuth endpoint works, but an AJAX request to same endpoint gives a CORS error?

We are trying to implement Github oAuth in our app using Passport.js. If the user hits the endpoint by clicking an anchor tag/href, it works fine, but if we use a click handler to initiate an ajax request instead, we receive a CORS error from the Github server. Why?
Server side code:
app.get('/auth/github',
passport.authenticate('github', { scope: [ 'user:email' ] }));
app.get('/auth/github/callback',
passport.authenticate('github', { failureRedirect: '/login' }),
function(req, res) {
console.log('Github authentication successful!');
res.redirect('/');
});
Client side code (we are using React):
--> Works:
<a href='/auth/github'>Contact</a>;
--> Does Not Work - CORS error:
handleContactAuth(event) {
$.ajax({
url: '/auth/github',
method: 'GET',
success: data => console.log( 'Contact Auth response: ', data),
error: err => console.log( 'Error connecting to GitHub.', err)
});
}
NOTE: This is a click handler on the React component and is functioning fine, as the ajax request is being triggered. I'm aware we're not handling the response currently, apart from just a console.log.
--> CORS Error we see on the Client side when using AJAX method instead of href:
XMLHttpRequest cannot load https://github.com/login/oauth/authorize? response_type=code&redirect_uri=ht…auth%2Fgithub%2Fcallback&scope=user%3Aemail&client_id=our_client_code. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.
Any ideas? Would appreciate any insights - many thanks.
CORS error is not an error returned by the server, but one triggered by the browser if the response doesn't contain HTTP headers signaling that cross-origin requests are allowed. The endpoint you are hitting obviously isn't designed to be accessed like this.
I had the same problem and I found that at least in Google Chrome XMLHttpRequest object is restricted to same origin policy. So you may need to stick to using an anchor tag.
Regular web pages can use the XMLHttpRequest object to send and receive data from remote servers, but they're limited by the same origin policy. Extensions aren't so limited. An extension can talk to remote servers outside of its origin, as long as it first requests cross-origin permissions.
Link: https://developer.chrome.com/extensions/xhr

Resources