I'm trying to get an access token from Azure. I was following this tutorial, but the thing is that the guy's using postman. It works for me in postman as well, but it fails in javascript and I don't understand why.
function getAccessToken() {
fetch(`${loginUrl}${tenantId}/oauth2/token`, {
method: "POST",
body: JSON.stringify({
grant_type: "client_credentials",
client_id: clientId,
client_secret: clientSecret,
resource: resource,
})
})
.then((response) => {
console.log(JSON.stringify(response));
})
.catch((err) => {
console.log(JSON.stringify(err));
});
}
The credentials are good, i.e. the clientId, secret, tenantid etc.
I also tried in PowerShell and it worked:
Invoke-RestMethod `
-Uri "$loginUrl$tenantId/oauth2/token" `
-Method Post `
-Body #{"grant_type"="client_credentials"; "resource" = $resource; "client_id" = $clientId; "client_secret" = $clientSecret }
But on js I get the following error:
Access to fetch at 'https://login.microsoftonline.com/myTenantId/oauth2/token' from origin 'null' has been blocked by CORS policy: 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.
I'm running this script in an HTML file for testing purposes at the moment.
If we directly call the rest api from a domain different from your website in the HTML page, we will get CORS issue. This is for safety reasons. For more details, please refer to here.
So if you want to get Azure AD token in HTML page, I suggest you use package msaljs to implement implicit flow to get token. The package has fixed cors issue. Regarding how to do that, please refer to here.
Besides, if you still want to use client credentials flow to get token in your HTML page. You have two choices. One choice is to use proxy server. The proxy acts as an intermediary between a client and server. For future details about it, please refer to the blog.
Related
I'm building a C++ backend with heavy calculations that are meant to work as an JSON API for connecting clients. To accomplish this, I've used HTTPServer in Poco::Net from POCO C++ Libraries.
Unfortunately when building two different clients it turned out that a regular webpage (HTML+JS) can't use Fetch to communicate with the backend due to CORS error. My understanding is that they need to use the same localhost: and that's not the case when manually opening the HTML document on the computer that's also running the backend.
All I can come up with when searching is the generic advice that servers need to enable CORS and whitelist relevant domains. Unfortunately I can't find documentation on how to accomplish this. The only relevant result was an answer on a related question where he recommended the following:
response.set("Access-Control-Allow-Origin", "*");
Naturally whitelisting everything isn't recommended from a security point of view but the main goal here is to just get it running locally to continue the development. Unfortunately it seems to make no difference and the browser console still says:
Access to fetch at 'http://localhost:6363/' from origin 'null' 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.
Hovering the error in the Chrome Network tab I get the following:
Cross-Origin Resource Sharing error: PreflightMissingAllowOriginHeader
My current JavaScript call:
const data = { test: 'test' }
fetch('http://localhost:6363', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
})
.then(response => response.text())
.then(message => {
console.log('Data retrieved:', message);
})
.catch((error) => {
console.error('Error:', error);
});
Any suggestions on how to proceed?
I'm using the Peloton API to generate statistics based on workout data grabbed from their API. Certain API requests require the user to be logged in, which can be done by sending your username and password to /auth/login. It returns a session ID that is needed to get those locked requests, such as workout history. The session ID is seemingly sent as a cookie (using credentials: 'include').
When I set credentials to include, it says "Access to fetch at (url) from origin (my site) has been blocked by CORS policy: 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'. How do I fix this? My code is below.
async function loginAndGetData(username, password) {
const info = { 'username_or_email': username, 'password': password };
const response = await fetch("https://pelotoncors.herokuapp.com/https://api.onepeloton.com/auth/login",
{
method: 'POST',
body: JSON.stringify(info)
});
const loginInfo = await response.json();
const workoutInfo = await fetch('https://pelotoncors.herokuapp.com/https://api.onepeloton.com/api/user/' + loginInfo.user_id + '/workouts?limit=1234567890',
{
method: 'GET',
credentials: 'include'
});
}
So I identified multiple problems:
Paleton doesn't have an official API or even an API doc (that doesn't make it impossible to use their API, but it can be difficult, and I would be cautious with that)
CORS
cors-anywhere
Logically, to prevent the use of the API by anybody, Paleton, like anybody else who builds a serious API, decided to put CORS headers on their responses, which is obviously not only from a security standpoint reasonable, but can be quite annoying because it makes it basically impossible to use the API from the browsers because the browser enforces the CORS-headers that are being set on responses by the servers.
So your first idea with cors-anywhere seems rational, but doesn't work because you use credentials: 'include' which requires the 'Access-Control-Allow-Origin' header to NOT be set to wildcard *.
If you are not familiar of what all that above means, let me run you through it:
In your above code, which I assume because of the above error message you run on a browser, you try to make a fetch call to cors-anywhere with the URL of the API and userId. Cors-anywhere makes the call to the API for you and ignores the CORS-Headers (it can do that because it is just a policy created for browsers to increase security), send you the data it gets from the API back BUT with the 'Access-Control-Allow-Origin' (by default) set to wildcard *. Because you use credentials: 'include' though, which requires the 'Access-Control-Allow-Origin' header do NOT be set on wildcard, your browser detects a CORS-policy violation, and you get the above error.
So what can you do now ?
Either you offload the API calls to your own backend (which is BTW always a better option), ignore the CORS by yourself and set the 'Access-Control-Allow-Origin' header appropriately or
Maybe there is a query you can add to the URL for cors-anywhere to change the 'Access-Control-Allow-Origin'? (But I don't know that) or
You look for an alternative
I guess the problem is your backend on Heroku, you need to set header "Access-Control-Allow-Origin": true on your backend.
Working with Apache Airflow REST API, and having issues with CORS.
When calling the endpoint using the fetch API in JavaScript I get the following error:
Access to fetch at 'my_url/api/v1/dags/example_bash_operator/tasks' from origin 'my_url' 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.
This is how I am calling it:
let url = "my_url/api/v1/dags/example_bash_operator/tasks";
let username = 'my_username';
let password = 'my_password';
let headers = new Headers();
headers.set('Authorization', 'Basic ' + btoa(username + ":" + password));
fetch(url, {
headers: headers,
method: 'GET',
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
})
.catch((error) => {
console.error('Error:', error);
});
I also tried adding mode: 'no-cors' but just get the "unexpected end of input" error.
For some background, the following works fine:
starting the airflow webserver and scheduler
accessing the airflow UI
accessing the SwaggerUI authenticating Swagger and calling the REST endpoints with this tool
calling my_url in the address bar of a new browser tab (returns the expected JSON)
I have set the auth_backend in airflow.cfg:
auth_backend = airflow.api.auth.backend.default
Although with the latest REST API version I don't think this makes a difference since everything is set to deny.
I have also set the access control headers in airflow.cfg as described in the docs:
access_control_allow_headers = origin, content-type, accept
access_control_allow_methods = POST, GET, OPTIONS, DELETE
access_control_allow_origin = my_url
...and also tried with wildcard for the access_control_allow_origin:
access_control_allow_origin = *
So the REST calls work fine through Swagger and through the browser address bar, but I cannot call it with fetch using JS. Note that the JS is in an index.html file on the same server (and same root directory) as the airflow files.
The described behavior makes sense, since CORS is used by the browser to prevent attacks from scripts of different resources.
You are still able to fetch via Swagger, Postman or other tools, even through the browser via address bar. But if the policy does not allow to fetch from a different origin, then the browser prevents fetching from your script, which is probably served on a different port. Origin contains host and port.
Your main issue, I cannot help with at the moment.
I've faced the issue of not being able to set the origin policy within the Airflow 2.0 server/API through the (docker-compose) environment variable AIRFLOW__API__ACCESS_CONTROL_ALLOW_ORIGIN.
Maybe it's related to your issue, since I can see from the url of your question (containing the v1), that you're are also using Airflow 2.x.
By the way, the message from chrome is CORS error: Preflight Missing Allow Origin Header, referring to the question in the comments of the original question.
I'm trying to access to introspect endpoint in my Keycloak server /openid-connect/token/introspect from my front app, but I get next error:
Access to fetch at 'http://localhost:8180/auth/realms/backoffice/protocol/openid-connect/token/introspect' from origin 'http://localhost:8080' 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.
Using Postman, curl or Node app this request works fine, but from my front-app using fetch method thows this error. I'm not sure it's possible query for introspect endpoint from front-app in the browser or if it's only possible from server app.
Other endpoints like:
openid-connect/token:
openid-connect/userinfo:
Works fine using the Postman JS code.
Keycloak config
My client in Keycloak has set up Web Origins * and Access Type confidential.
Client Code
My front app is simply the Postman code JS, and I deploy it using node http-server.
var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
var urlencoded = new URLSearchParams();
urlencoded.append("client_id", "my-client");
urlencoded.append("client_secret", "my-secret");
urlencoded.append("token", "eyJ...oCA");
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: urlencoded,
redirect: 'follow'
};
fetch("http://localhost:8180/auth/realms/backoffice/protocol/openid-connect/token/introspect", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
Header Response
The header response in userinfo endpoint comes with Access-Control-Allow-Origin and Access-Control-Allow-Credentials but is not present in introspect endpoint.
From the looks of it, the Keycloak server prevents the CORS headers to be set for the introspection endpoint. This could be a bug or by design. I tried it and I get the same error.
If you really want to access the introspect endpoint from the web app, you could set up a NGINX reverse-proxy in front of your Keycloak server and use it to add the missing headers.
That being said, according to oauth.com you should not leave the introspection endpoint available to the public, which is what you are currently doing since anyone can retrieve the client id and secret from your web app.
If the introspection endpoint is left open and un-throttled, it presents a means for an attacker to poll the endpoint fishing for a valid token. To prevent this, the server must either require authentication of the clients using the endpoint, or only make the endpoint available to internal servers through other means such as a firewall.
This could explain the decision not to allow CORS.
Another thing, it looks like you forgot to set the token_type_hint check out this stackoverflow post for more information.
Before I start, I'd like to say sorry for my English, it's not my native language.
I'm trying to setup OAuth2 for GitHub authorization.
I stucked at the step, where I should send POST request to github and receive access token. The problem is that when I send POST request my browser automatically downloads file with access token. Since I can't open this file with javascript, I'm trying to get json as response.
In the documentation it's written that I can change accept header and receive json, but I can't write correct POST request.
I've already tried a lot of things, like this:
$.ajax({
method: "POST",
url: "https://github.com/login/oauth/access_token",
dataType: "application/json"
});
or
$.ajax({
url: 'https://github.com/login/oauth/access_token',
headers: {
Accept : "application/json",
}
data: "data",
success : function(response) {
console.log(response);
} })
etc
But I get this error:
XMLHttpRequest cannot load github.com/login/oauth/access_token. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://braga.fedyunin.com.ua' is therefore not allowed access. The response had HTTP status code 404.
Can't find any useful information in google, so I had to register here. Thanks for help.
Read https://developer.github.com/v3/ in section: Cross Origin Resource Sharing
I tried the same thing, but also failed due to the lack of the Access-Control-Allow-Origin header in the response from GitHub API. I contacted GitHub support and found out what was going wrong.
It doesn't work because you are attempting to use OAuth from a web application, which GitHub API does not support. When you authenticate this way, your client_id and client_secret must be in the web page somewhere and sent with the POST request. The entire request, including your client_secret, can be viewed with Firebug or a similar tool. Because it's a bad idea to expose your client_secret, GitHub API will not return the Access-Control-Allow-Origin header, thus preventing you from retrieving the token.
You must issue the POST from the server side and get the token that way. When you do that, the client_secret is on your server, not in people's browsers.
The Ajax request from your site to github.com fails because browsers follow the same origin policy for xhr requests. This means that an xhr request can only be made for a resource on the same origin.
To allow for cross origin requests, the server needs to Whitlelist domains that can access a particular resource.
In your case, to do this, you need to register your site as an application on your github account, by entering the details here:https://github.com/settings/applications/new