Cross-Domain Ajax Requests WSO2 IS - ajax

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.

Related

Getting CORS Error when using Google Business API

I am using google business API and trying to get location list.
I am going trough their documentation and using project from the link below as basis
https://developers.google.com/my-business/content/implement-oauth
Using that project I am able to successfully retrieve accounts list.
The problem occures when I try to retrieve locations list using accountID. Here is a link for their documentation
https://developers.google.com/my-business/content/manage-locations
Acording to documentation, to get location list for specific account, I should use following request
GET
https://mybusinessbusinessinformation.googleapis.com/v1/{accountId}/locations
Authorization: Bearer <access_token>
This is the code snippet, that I added to their sample project
function retrieveGoogleMyBusinessLocations(accessToken) {
$.ajax({
type: 'GET',
url: 'https://mybusinessbusinessinformation.googleapis.com/v1/{accID}/locations',
headers: {
'Authorization' : 'Bearer ' + accessToken
},
success: function(returnedData) {
var e = document.createElement("pre")
e.innerHTML = JSON.stringify(returnedData, undefined, 2);
document.body.appendChild(e);
}
});
}
When I do this request, it gives "CORS error".
The error in the console is following
Access to XMLHttpRequest at 'https://mybusinessbusinessinformation.googleapis.com/v1/xxx/locations' from origin 'http://localhost:8001' 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.
GET https://mybusinessbusinessinformation.googleapis.com/v1/xxx/locations net::ERR_FAILED
From the error message it seems that server does no accept requests from localhost:8001, but if I do request to different endpoint it will return result.
For example if I change utl from
https://mybusinessbusinessinformation.googleapis.com/v1/{accID}/locations
to
https://mybusinessbusinessinformation.googleapis.com/v1/accounts/{accID}/locations?readMask=categories
With the second url it will return successfull result.
I am confused why it is allowing requests to one endpoint and blocks requests to other endpoint.
Can anyone help with this problem?
Have you tried making direct API requests via the Google Developers OAuth 2.0 Playground?
I tried to reproduce your error but got the expected 404 Not Found response for the unsupported endpoint pattern.

Access to fetch has been blocked by CORS policy. It does not have HTTP ok status

So I'm building a react app that fetches JSON data from a spring boot rest api built by me.
Here is the code for the fetch method:
componentDidMount() {
fetch(`http://localhost:8080/students`, {
headers : {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then((response) => response.json())
.then((data) => this.setState({students: data}));
console.log(this.state.students);
}
However when I run the program it gives me an error saying:
Access to fetch at 'http://localhost:8080/students' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
Can anyone help me?
I'm not 100% familiar with Spring Boot, but the general solution to this problem is to make sure your service responds with an Access-Control-Allow-Origin header that matches the origin (localhost in your example) if it is not the same origin as your service.
Adding "Access-Control-Allow-Origin": "*" would do it for your development purposes. In production, you probably want to be more specific with which origins are actually allowed.
Have a look at this resource for more information about CORS: https://enable-cors.org/
It is the same origin policy implemented in your browser that is causing this. It specifies that a browser should allow scripts in one web page to access resources on another, but only if they are from the same origin. If they are not, you can specify that they are allowed by specifying the header I mentioned above. You may also need to specify allowed verbs and headers as well, depending on what you're doing.

Twilio Auth API is not working my in local system

I had integrated Twilio Auth API in my React project i getting
fetch('https://api.authy.com/protected/json/phones/verification/start', {
method: 'POST',
body: JSON.stringify(resObject),
dataType : 'json',
headers: {
'Accept': 'application/json',
'content-type': 'application/json',
'X-Authy-API-Key': 'XXXXXXXXXXXXXXXXXXXXXXXXXXX',
},
})
I am getting this error
Fetch API cannot load https://api.authy.com/protected/json/phones/verification/start. Response for preflight has invalid HTTP status code 401
I Now this is a cross-origin issue but I am not able to fix it
Authy developer evangelist here.
It is a very bad idea to include your Authy API key in the client side of your application. A malicious user could take your API key and use it to abuse your users via the Authy API.
We recommend that you perform your API requests on the server side, so that no-one can get at your API key. If you are using Node.js as a server, there is an Authy Node module to make this nice and easy. There are libraries available for other languages too.

identity Server - Configuring CORS for bearer options

I am testing the jquery ajax calls to the API server from a different domain. Unfortunately I am getting an OPTIONS error. Here is my request code:
$.ajax({
url: "https://localhost:44356/api/Default/",
headers: {
"Authorization": "Bearer " + user.access_token
},
success: function (res) {
logAjaxResult(res);
},
error: function() {
logAjaxResult('Error');
}
}))
Which gives
XMLHttpRequest cannot load https://localhost:44356/api/Default/. Response for preflight has invalid HTTP status code 405.
Normally this is an easy fix - I install Microsoft.AspNet.WebApi.Cors, set up a provider and allow OPTIONS through always. I can see how I would normally do this on the Identity Server box too as there is a CorsProvider you can register up. My issue however is on the API box I am using IdentityServerBearerTokenAuthenticationOptions and I see no CORs options. When I try to set up the WebAPI.cors provider though I get an error saying there are multiple origins set on the server to allow. This indicates to me (correct me if I'm wrong) that the WebApi box has somehow got the CORs settings from my identity server box that is registered as it's authority. Is this right?
How do I configure to allow pre-flight requests with app.UseIdentityServerBearerTokenAuthentication(options)?
Many thanks
This issue was resolved when I found the documentation uses
Microsoft.Owin.Cors
I was using the package
Microsoft.AspNet.WebApi.Cors

ajax get request to Office365 REST Api fails CORS?

I'm attempting to make an ajax GET request to the Office365 RESTful API service from my local server, but am running into cross-domain HTTPRequest errors. The following is a sample of my 'get-files-at-root' attempt:
$.ajax({
url: 'https://[sharepoint_site]/_api/v1.0/me/files?access_token='+token,
type: 'get',
dataType: 'json',
success: function(data) {
if (success){
success(data);
}
},
error: error
})
I'm getting the following response from the server:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 403.
I've tried sending the access token as a header parameter:
headers: {'Authorization': 'Bearer '+ token}
but this had the same result.
Any ideas on what I'm doing wrong?
(Background: I'm trying to create my own Office365 'file picker' on the client because I couldn't find an available library for OneDrive Business that supplies this.)
Office 365 Files API and SharePoint REST have just introduced support for CORS.
https://msdn.microsoft.com/en-us/office/office365/howto/create-web-apps-using-CORS-to-access-files-in-Office-365
What you were trying to do is exactly how it works. The service will respond to the OPTIONS pre-flight request with an Access-Control-Allow-Origin header.
The authorization in the request must be an Azure Active Directory issued OAuth2 implicit grant access token.
You have no idea about CORS. Read the specification: http://www.w3.org/TR/cors/
In your case you have to allow null origin, since we are talking about localhost. You have to allow the methods and the headers you send, even the content-type header. You have to allow sending credentials, which you can get in the Authorization header. You have to handle OPTIONS requests with 200 ok.
response.setHeader("Access-Control-Allow-Origin", "*");
response.setCharacterEncoding("UTF-8");
response.setHeader("Access-Control-Allow-Methods", "POST, GET");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
Can you try with setting the Access-Control-Allow-Origin in header as shown below.
headers: { 'Access-Control-Allow-Origin': '*' }

Resources