I would like to unblock cors in all requests that occurs in www.example.com via xhr for example in it i request to www.google.com how can i add response headers for it like Access-Control-Allow-Origin: www.example.com
var corsorg = {
name: "Access-Control-Allow-Origin",
value: "https://www.example.com"
};
var corstrue = {
name: "Access-Control-Allow-Credentials",
value: "true"
};
e.responseHeaders.push(corsorg);
e.responseHeaders.push(corstrue);
console.log(e);
},
{urls: ["<all_urls>"]},
["blocking", "responseHeaders"]
);
Related
I've created a variable to hold the client ID (CLIENT_ID) but I keep getting an error message saying that the client ID is required when running this function. Anyone have any idea of what I've done wrong here?
function getAuth() {
var authBasedUrl = 'https://test-api.service.hmrc.gov.uk/oauth/authorize';
var response = UrlFetchApp.fetch(authBasedUrl, {
headers: {
'Accept' : 'application/vnd.hmrc.1.0+json',
'response_type': 'code',
'client_id' : CLIENT_ID,
'scope' : 'hello',
'redirect_uri' : 'https://www.xxxxxxx.com/'
}});
var result = JSON.parse(response.getContentText());
Logger.log(JSON.stringify(result, null, 2));
}
Based on the docs you need to make a POST request. There is a blockqoute on the page that says:
Include the request parameters in the request body, not as request
headers.
EDIT:
function getAuth() {
var authBasedUrl = 'https://test-api.service.hmrc.gov.uk/oauth/token';
var options = {
headers: {
'Accept': 'application/vnd.hmrc.1.0+json',
"Content-Type": "application/json"
},
payload: JSON.stringify({
client_id: 'RgwU6hvdxxxxxxic6LwIt',
client_secret: '9e8c9yyyyyyyyyyc2fc2ed9126',
grant_type: 'client_credentials',
scope: 'hello'
})
}
var response = UrlFetchApp.fetch(authBasedUrl, options);
var result = JSON.parse(response.getContentText());
console.log(result);
}
I'm trying to receive an access token from the Zoom api via Oauth. No matter what form I try and send the body as, 'Content-Type': 'application/json' or Content-Type:application/x-www-form-urlencoded, it always errors to { reason: 'Missing grant type', error: 'invalid_request' }.
var options = {
method: "POST",
url: "https://zoom.us/oauth/token",
body: JSON.stringify({
grant_type: "authorization_code",
code: process.env.AUTH_CODE,
}),
redirect_uri: "https://zoom.us",
};
var header = {
headers: {
Authorization:
"Basic " +
Buffer.from(process.env.ID + ":" + process.env.SECRET).toString("base64"),
},
"Content-Type": "application/json",
};
var tokCall = () =>
axios
.post("https://zoom.us/oauth/token", options, header)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error.response);
});
tokCall();
I'm fairly certain the answer lies in either the data type in which Oauth is receiving the data, or where/if it's receiving the body at all. Any suggestions would be gratefully received.
The error is being thrown because you're sending the data as the body of the post request when the Request Access Token Zoom API is expecting to find them as query parameters which you might know as query strings.
Reference
https://marketplace.zoom.us/docs/guides/auth/oauth#local-test
Image of page from link to highlight the use of query parameters and content-type requirement for API call
Change
var options = {
method: "POST",
url: "https://zoom.us/oauth/token",
body: JSON.stringify({
grant_type: "authorization_code",
code: process.env.AUTH_CODE,
}),
redirect_uri: "https://zoom.us",
};
to
var options = {
method: "POST",
url: "https://zoom.us/oauth/token",
params: {
grant_type: "authorization_code",
code: process.env.AUTH_CODE,
redirect_uri: "<must match redirect uri used during the app setup on zoom>"
},
};
The Content-Type header should be set to application/x-www-form-urlencoded as this is a requirement of the zoom API itself.
BTW, axios requires you to name the body field/object of your request as data and also there's no need for JSON.stringify() method since axios does that for you under-the-hood
Though it's a late answer, I'd like to share it since it took me some time to complete this using Axios.
So to make Zoom authorization, you need to do:
Base64 encode the secret and client id
const base64EncodedBody =
Buffer.from(`${ZOOM_CLIENT_ID}:${ZOOM_CLIENT_SECRET}`).toString('base64');
URI encode the grant_type, code and redirect_uri
const data =
encodeURI(`grant_type=authorization_code&code=${code}&redirect_uri=${redirectUri}`);
Send the request
const response = await axios.post('https://zoom.us/oauth/token', data, {
headers: {
Authorization: `Basic ${base64EncodedBody}`,
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(data),
},
});
var cors = require("cors");
cors({ origin: '*' });
cors({ allowHeaders: 'X-PINGOTHER'});
cors({ methods: 'GET,HEAD,PUT,PATCH,POST,DELETE'});
exports.endpoint = function(request, response) {
let text = '100,000';
response.writeHead(200, { 'Content-Type': 'text/plain' });
response.end(text);
}
I am running this on Runkit and still get the error when checking on a website, where I want to display this return value:
"No 'Access-Control-Allow-Origin' header is present on the requested resource"
In your example you've loaded the cors module and configured it, but not actually done anything to get it to intercept the HTTP request and send back your CORS headers.
If you're just using a simple Runkit endpoint, you don't need the CORS module at all – just add the headers in your endpoint, where you're already adding the Content-Type header:
exports.endpoint = function(req, res) {
res.writeHead(200, {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': '*',
});
res.end('foo');
};
There appears to be a conflict between the validation of the request and the requirements of the request. The API call requires that the scope be set to 'app'. It also requires a userId. However, when the two are combined you get the below messages indicating you cannot combine the two.
API https://docs.smooch.io/rest/#pre-create-app-user
REQUEST
{ host: 'api.smooch.io',
path: '/v1/appusers',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token}`
}
Example body.
{
scope: 'app',
userId: 'some_userId',
credentialRequired: true,
email: 'test#email.com',
properties: { picture: 'https://s.gravatar.com/avatar/.....' }
}
RESPONSE BODY
{"error":{"code":"bad_request","description":"Invalid JWT body. Cannot use userId param with app scope"}}
RESPONSE HEADERS
{ connection: 'close',
server: 'nginx',
date: 'Tue, 21 Feb 2017 14:47:50 GMT',
'content-type': 'application/json; charset=utf-8',
'content-length': '105',
'x-powered-by': 'Express',
vary: 'X-HTTP-Method-Override',
etag: 'W/"69-huba/v8EazhrDAoySthrKw"',
via: '1.1 vegur' },
statusCode: 400,
statusMessage: 'Bad Request' }
I think you might be confusing two separate concepts - the JWT payload vs the HTTP request body.
scope is defined in the payload of your JWT credential (Bearer ${token} in your code sample). More information about JWTs and scopes can be found here.
userId should be specified in the HTTP request body.
I'm not sure what language you're using, but here's an example in Node.js:
var jwt = require('jsonwebtoken');
var token = jwt.sign({ scope: 'app' }, SECRET, { headers : { kid: KEY_ID } });
var request = require('request');
request.post({
url: 'https://api.smooch.io/v1/appusers',
headers: {
'Authorization': `Bearer ${token}`
},
json: {
userId: 'some_userId',
credentialRequired: true,
email: 'test#email.com',
properties: { picture: 'https://s.gravatar.com/avatar/.....' }
}
});
I'm writing my login form which provides for a put request to the server.
The communication protocol is JSON
I have to send username and password hashes, using CryptoJS with SHA-256 hash algorithm.
Authentication data must be stored encrypted in the browser as a cookie, and each request is sent to the server as the basis for authentication, when you close the browser window, the data must be deleted.
example put request:
PUT my api adress
{"loginRequest": {
"username": "admin",
"hash": "8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918"
}}
Response OK
Code: 200
{"loginResponse": {
"username": "admin",
"name": "Example Admin",
"roles": [
"USER", "ADMIN"
],
"lastLogin": "2014-02-17+01:00",
"backendVersion": "katconnect-backend-0.0.1-SNAPSHOT"
}}
Response Data Validation Error (URI username <> JSON username)
Code: 400
{"error": {
"code": "400",
"message": "the message of the error"
}}
Response Authentication Error (username or hash is null, user not found, wrong hash value)
Code: 401
{"error": {
"code": "401",
"message": "Username or password false"
}}
Here is my code:
angular.module('validationApp')
.controller('loginCtrl',function ($scope,$http,Base64,$cookieStore) {
$scope.login = function () {
var user = {
username: $scope.username,
hash: CryptoJS.SHA256($scope.password)
};
var loginRequest = JSON.stringify(user);
var credentials = Base64.encode($scope.username + ':' + $scope.password);
$http({
method: 'PUT',
url: url+'/users/'+ $scope.username +'/login',
data: loginRequest,
headers:{'Content-Type': 'application/json'}
})
.success(function (){
$http.defaults.headers.common['Authorization'] = 'Basic ' + credentials;
$cookieStore.put( authCookieKey ,credentials);
})
.error(function(code){
if (401 === code) {
$scope.invalidUsernamePassword = true;
}
})
};
})
You are doing a cross domain request to the API server. The browser first sends a options request to see if the HTTP method is allowed. Have you setup up CORS middleware from your server? If yes check if the method PUT is in whitlist.
http://better-inter.net/enabling-cors-in-angular-js/