tfs extension Origin 'null' is therefore not allowed access - ajax

I encounter a problem when I try to call the Teamcity REST service through a TFS extension.
I configured TeamCity as well:
rest.cors.origins = "http://my.tfsserver"
rest.cors.optionsRequest.allowUnauthorized = true
In the TFS extension, I call the following url:
http: //my.teamcity.server:80/app/rest/latest/projects using "XMLHttpRequest"
const pair :string=this.settings.username+":"+this.settings.password;
const encodedCreds:string = btoa(pair);
const basicAuthValue:string = "Basic "+ encodedCreds;
const apiurl:string="/app/rest/latest/projects";
const completeUrl:string = this.settings.urlTeamCity+apiurl;
const xhr = new XMLHttpRequest();
xhr.open("GET",completeUrl,true);
xhr.setRequestHeader('Authorization', basicAuthValue);
xhr.setRequestHeader("Access-Control-Allow-Origin" ,"http://my.tfsserver");
xhr.onload=function(){
console.log(xhr.responseText);
}
xhr.onerror=function(){
console.log(xhr.response);
}
xhr.send();
I'm getting the following error in the console:
Failed to load http://my.teamcity.server:80/app/rest/latest/projects:
Response for preflight is invalid (redirect)
In the TeamCity rest log, i have the following two lines:
[2018-10-01 14:12:49,891] DEBUG [p-nio-80-exec-9] -
er.rest.APIController/rest-api - Got CORS request from origin 'null',
but this origin is not allowed. Add the origin to 'rest.cors.origins'
internal property (comma-separated) to trust the applications hosted
on the domain. Current allowed origins are: Enabled CORS Origins:
[http://my.tfsserver]
[2018-10-01 14:12:49,892] DEBUG [p-nio-80-exec-9] -
er.rest.APIController/rest-api - REST API request processing finished
in 1ms, status code: 302, request: OPTIONS
'/app/rest/latest/projects', from client 10.69.152.71:59256, no auth
Based on the last line, i modify my code to:
...
xhr.open("GET",completeUrl,true,this.settings.username,this.settings.password)
xhr.withCredentials=true;
...
but, i'm still getting the same error in both chrome console and team city rest log.
in the chrome console, on the network tab, i can see that "origin" header is null but i don't understand why?
Thanks by adavance for any help :)

Related

AJAX POST with CORS to API Gateway does not work

I'm getting this error message: Access to XMLHttpRequest at 'https://########.execute-api.us-east-1.amazonaws.com/prod' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
I tried adding add the following code with no luck:
beforeSend: function(xhr) {
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
xhr.setRequestHeader("Access-Control-Allow-Methods", "OPTIONS,POST");
xhr.setRequestHeader("Access-Control-Allow-Headers", "Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token");
xhr.setRequestHeader("Content-Type", "application/json");
}
What am I missing?
Answered my own question. The invoke URL shows the stage but you have to add the resource name, duh :)
Instead of this you can also use npm module cors. Just fixed my problems with it.
const cors = require('cors');
const app = express();
app.use(cors());
app.options('*', cors());

How do I make AJAX calls to a JSON file in my Github repository

I have written this simple javascript code to perform a get request on my github repository
var url='https://github.com/mypath/AjaxPractice/myFile.json';
myBtn.addEventListener('click', function(){
let XHR = new XMLHttpRequest();
XHR.open('GET', url, true)
XHR.setRequestHeader('Access-Control-Allow-Origin','*');
XHR.onload = function() {
if (this.status === 200) {
console.log(JSON.parse(this.responseText));
}
}
XHR.send();
});
However I get this error message:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://github.com...(Reason: CORS header 'Access-Control-Allow-Origin' missing).
What is missing here?
If a correct request is not allowed because of CORS , you have no options other than use something something like CORS-ANYWHERE here: https://github.com/Rob--W/cors-anywhere
This is how I managed to do it:
Go to your github repo and click on settings
Scroll down to where it says source and change it from none to master branch.
Note: the example I used didnt require XHR.setRequestHeader('Access-Control-Allow-Origin','*');

Nuxtjs Axios in Vuex Module CORS error

I am using Nuxtjs and built-in Vuex modules along with Nuxtjs's official axios. I'm trying to GET from my local server and it always throw CORS error.
So I made an API call to Github's public endpoint, and unsuccessfully only getting CORS error in my console.
I'm using Store actions to launch AJAX calls to server on component create lifecycle. Here is my code.
// component.vue
created () {
this.$store.dispatch('getGithubAPI')
}
// store action
async getGithubAPI ({ commit, state }) {
await this.$axios.$get('https://api.github.com/users/kaungmyatlwin', { headers: { 'Access-Control-Allow-Origin': '*' } })
.then(resp => {
console.log(resp.data)
})
}
Still no luck of getting it. Here is an error message that was thrown to console.
Failed to load https://api.github.com/users/kaungmyatlwin: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:3000' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
What did I do wrong here? Or is it an error residing in async/await?
UPDATE: Strange thing is that the network call actually goes out and fetch data from server, as it can be seen in Network console from Chrome.
Ok I seem to have figured out this problem.
In nuxt.config.js, you have to put credentials: false to allow CORS wildcard.
My axios config here.
axios: {
baseURL: 'https://api.github.com',
proxyHeaders: false,
credentials: false
}
Reference: https://github.com/nuxt-community/axios-module#credentials

CORs error when accessing Square V2 API

I'm making a client-side request out to V2 of the Square API using Vue and Axios. My Vue component is as follows:
import axios from 'axios';
export default {
mounted() {
var instance = axios.create({
baseURL: 'https://connect.squareup.com/v2/',
timeout: 1000,
headers: {
'Authorization': 'Bearer xxxxxxxxxxxxxxxxx',
'Accepts': 'application/json',
'Content-Type': 'application/json'
}
});
instance.get('catalog/list')
.then(function (response) {
console.log(response);
}) ;
}
}
However, when I make that call, I receive the following error:
Failed to load https://connect.squareup.com/v2/catalog/list: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://local-env.dev' is therefore not allowed access. The response had HTTP status code 403.
That error suggests that there is some configuration that has to happen on the Square side, but I saw no opportunity to whitelist domains, etc.
Has anyone come across this error before, regardless of service, and if so, how did you resolve?
I don't think the Square API supports being called from a browser. I used Postman to do an OPTIONS request on https://connect.squareup.com/v2/catalog/list and the response was a NOT_FOUND. The OPTIONS request is needed for proper CORS support.
Plus, if you did this, I would think your auth token would need to be sent to the client -- thus exposing it to everyone. It looks like the Square API is only designed to be called from a server. But that is just based on me skimming the docs a bit. I have no experience using their API.
When doing OAuth authorization request you are not supposed to do it from your application. Create and URL with the parameters and open it in a new browser window or tab, Something like:
const grants='MERCHANT_PROFILE_READ CUSTOMERS_READ CUSTOMERS_WRITE PAYMENTS_READ PAYMENTS_WRITE PAYMENTS_WRITE_ADDITIONAL_RECIPIENTS PAYMENTS_WRITE_IN_PERSON';
const params = new HttpParams()
.set('scope', grants)
.set('client_id', <YourSquareApplicationId>)
.set('state', '1878789');
const requestUrl = `${<squareUrl>}/oauth2/authorize?${params.toString()}`;
window.open(requestUrl, "_blank");
That new window is supposed to ask the end user to login to his account and accept or deny the request.

How come I keep getting a "Request failed with response code 401" when trying to push via Urban Airship?

I have double, triple, and quadruple checked that I have the right master key that I'm passing. My parameters are taking directly from the UA website also so it can't be that. Anyone see what I'm doing wrong here???
Parse.Cloud.define("sendPush", function(request, response) {
var Buffer = require('buffer').Buffer;
var parameters = {
"audience" : "all",
"device_types" : "all",
"notification" : {
"alert" : "Hello from Urban Airship."
}
};
var params = JSON.stringify(parameters);
Parse.Cloud.httpRequest({
url: "https://go.urbanairship.com/api/push/",
method: 'POST',
headers: {
"Content-Type" : "application/json",
"Authorization" : 'Basic ' + new Buffer('MASTER_KEY').toString('base64'),
"Accept" : "application/vnd.urbanairship+json; version=3;"
},
body: params,
success: function(httpResponse) {
response.error(httpResponse);
},
error: function(httpResponse) {
response.error('Request failed with response code ' + httpResponse.status);
}
});
});
I've also tried adding in APP_SECRET:
"Authorization" : 'Basic ' + new Buffer('APP_SECRET':'MASTER_KEY').toString('base64'),
It's not clear from your code sample if you are including the app key in your request. API requests to Urban Airship use HTTP basic authentication. The username portion is the application key and the password portion in this case is the master secret. The application secret is restricted to lower-security APIs and is for use in the distributed application. The master secret is needed for sending messages and other server API requests.
Urban Airship provides a guide for troubleshooting common API issues.
I had the same problem and tried to figure it out by Network diagnosing tools for more than two days. Because after debugging I checked that I send the right credentials to UA. After all I called the UA and ask them to check the Credentials (in my case was appKey and appToken for streaming with java-connect API) if they are still valid. They checked and approved the validation but just in case sent me a new credentials. And I could connect with the new credentials!
It is for sure a bug by UA because I tested the whole time by another test application, which was a Desktop java application and I could connect to the server (with the same appKey and appToken) and get the events, but I got 401 error in my main Application, which was a Web Application running on TomCat 8.0 . It means It worked in a same time in with the same credential for one application and did not work for another application.

Resources