Getting UNAUTHORISED ERROR 401 - Sendgrid API - javascript

I am trying to perform actions on sendgrid lists via their API.
https://sendgrid.com/docs/API_Reference/Web_API_v3/Marketing_Campaigns/contactdb.html#List-All-Lists-GET
I'm using this to set up my code however I'm getting Error 401 UNAUTHORISED when performing the request via $http in my Angular app.
I tried making the same request in Python and that seemed to working fine though.
var head = {'Authorization': 'Bearer SG.PE-XXXXXXXXXXXXXXXXXXXXXX'};
var sgUrl = "https://api.sendgrid.com/v3/contactdb/lists";
self.$http({
method : "GET",
url : sgUrl,
headers : head,
}).then(function mySuccess(response) {
alert(1);
}, function myError(response) {
alert(0);
});
Thanks!

Related

How to fix wrong API request in Cypress?

I am trying to create API request for login to chess.com site, but it looks like the request fails. Steps to reproduce:
I send the request manually and check it in Google developer tools. Here is the result:
Request URL: https://www.chess.com/login_check
Request Method: POST
Form Data
_username: user#test.com
_password:1234567
login:
_target_path: https://www.chess.com/
_token: cQr-epETT8R1cTUDY-AFua1cHdE46sHqY3OyDXgDz_k
I created GET request in Cypress for getting the token and then used this token along with my credentials in my POST request to the server to be logged in. Here is my request:
describe("Login via API", () => {
it("Send request for the token", () => {
cy.request("GET", basicLinks.loginUrl).then((response) => {
const token = Cypress.$(response.body).find("#_token").attr("value");
cy.request({
method: "POST",
url: "/login_check",
form: true,
body: {
_username: "test#yahoo.com",
_password: "12345",
login: {
_target_path: "https://www.chess.com/",
_token: token,
},
},
});
});
});
});
But it look that there is something wrong with the request because as far as I can see I got the initial login page as the server response. Could anybody advise what I am doing wrong and how can I fix my request? Please find attached screenshot containing the data mentioned above.

Axios post request not sent to external url: TypeError: ns.GetCommandSrc is not a function

I got a react app sending some post, get etc requests to an external URL using axios (^0.19.2). The get requests are sent and received properly, though post requests trigger a JS error and are even not sent:
TypeError: ns.GetCommandSrc is not a function
Checking the reference brings me to this method:
function GetCommandUrl()
{
var commandSrc = ns.GetCommandSrc() + "/to/ajaxRequestNotify";
return (document.location.protocol === "https:") ? commandSrc.replace("http:", "https:") : commandSrc;
}
My code is actually pretty simple:
componentDidMount = () => {
const accessToken <my access token>;
axios({
method: 'post',
url: 'http://<remote url>/customer/check',
data: {access_token : accessToken}
})
.then(response => {
console.log(response.data);
});
}
-- UPDATE AFTER SOLVING THE ISSUE --
This function is coming from Kaspersky javascript injection. Solved it by disabling Inject scripts into web traffic to interact with web pages
In Kaspersky: Settings -> Additional -> Network -> Inject scripts into web traffic to interact with web pages.

Google reCAPTCHA, 405 error and CORS issue

I am using AngularJS and trying to work with Google's reCAPTCHA,
I am using the "Explicitly render the reCAPTCHA widget" method for displaying the reCAPTCHA on my web page,
HTML code -
<script type="text/javascript">
var onloadCallback = function()
{
grecaptcha.render('loginCapcha', {
'sitekey' : 'someSiteKey',
'callback' : verifyCallback,
'theme':'dark'
});
};
var auth='';
var verifyCallback = function(response)
{
//storing the Google response in a Global js variable auth, to be used in the controller
auth = response;
var scope = angular.element(document.getElementById('loginCapcha')).scope();
scope.auth();
};
</script>
<div id="loginCapcha"></div>
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>
So far, I am able to achieve the needed functionality of whether the user is a Human or a Bot,
As per my code above, I have a Callback function called 'verifyCallback' in my code,
which is storing the response created by Google, in a global variable called 'auth'.
Now, the final part of reCAPCHA is calling the Google API, with "https://www.google.com/recaptcha/api/siteverify" as the URL and using a POST method,And passing it the Secret Key and the Response created by Google, which I've done in the code below.
My Controller -
_myApp.controller('loginController',['$rootScope','$scope','$http',
function($rootScope,$scope,$http){
var verified = '';
$scope.auth = function()
{
//Secret key provided by Google
secret = "someSecretKey";
/*calling the Google API, passing it the Secretkey and Response,
to the specified URL, using POST method*/
var verificationReq = {
method: 'POST',
url: 'https://www.google.com/recaptcha/api/siteverify',
headers: {
'Access-Control-Allow-Origin':'*'
},
params:{
secret: secret,
response: auth
}
}
$http(verificationReq).then(function(response)
{
if(response.data.success==true)
{
console.log("Not a Bot");
verified = true;
}
else
{
console.log("Bot or some problem");
}
}, function() {
// do on response failure
});
}
So, the Problem I am actually facing is that I am unable to hit the Google's URL, Following is the screenshot of the request I am sending and the error.
Request made -
Error Response -
As far as I understand it is related to CORS and Preflight request.So what am I doing wrong? How do I fix this problem?
As stated in google's docs https://developers.google.com/recaptcha/docs/verify
This page explains how to verify a user's response to a reCAPTCHA challenge from your application's backend.
Verification is initiated from the server, not the client.
This is an extra security step for the server to ensure requests coming from clients are legitimate. Otherwise a client could fake a response and the server would be blindly trusting that the client is a verified human.
If you get a cors error when trying to sign in with recaptcha, it could be that your backend server deployment is down.

Trying to get basic authentication work in angularJS

I have a RESTful back-end server enabling the basic authentication. I would like to implement a GET request in my angularJS file to get some data from the server.
Code:
angular.module('MyApp', [])
.controller('MyCtrl',function ($scope, $http) {
var userheader= btoa('username' + ':' + 'userpassword');
$scope.getData= function (){
var req = {
method: 'GET',
url: 'https://localhost:8000/data/',
headers: { 'Authorization': 'Basic ' + userheader }
};
$http(req)
.success(function(data) {
$scope.mydata = data;
}).error(function(){
throw new Error('Somthing went wrong');
});
};
});
When I invoked the function 'getData()', it always give me the error "No 'Access-Control-Allow-Origin' header is present on the requested resources".
Your REST server needs to support CORS requests in order to respond to client-generated requests.
Which framework is your server built with?
It is usually a bad idea (security wise) to use HTTP Basic authentication, even over TLS, in untrusted client applications (JS or mobile). Any reason you're not using Token Authentication for Single Page Applications ?

Accessing Twitter with Django and Javascript

This is a follow up to a previous question I had posted here.
Basically I've been trying to implement a way to send request to twitter oauth resources via javascript. I have a server running a Django application which uses Django-social-auth to register users to Tiwtter. After I've obtained authorisation I get a users access_token and oauth_token_secret.
On the client side I have a javascript application which calls my server to compute the appropriate headers, which I do by using python oauth2. The piece of code doing this is as follows:
url = request.POST['url']
params = {
'oauth_version': "1.0",
'oauth_nonce': oauth.generate_nonce(),
'oauth_timestamp': int(time.time()),
}
at = social.extra_data['access_token'].split('&oauth_token=')[1]
ats = social.extra_data['access_token'].split('&oauth_token=')[0].split('oauth_token_secret=')[1]
token = oauth.Token(key=at, secret=ats)
consumer = oauth.Consumer(key=settings.TWITTER_CONSUMER_KEY, secret=settings.TWITTER_CONSUMER_SECRET)
params['oauth_token'] = token.key
params['oauth_consumer_key'] = consumer.key
req = oauth.Request(method="GET", url=url, parameters=params)
signature_method = oauth.SignatureMethod_HMAC_SHA1()
req.sign_request(signature_method, consumer, token)
This request parameters are then sent to the client which does the call to Twitter using these parameters:
$.ajax({
url: "https://api.twitter.com/1/statuses/home_timeline.json",
data: parameters,
dataType: 'jsonp',
success: function(twitter_data) {
console.log('twitter_data = ', twdata);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('err = ', textStatus);
console.log('err = ', errorThrown);
}
});
which generates a request for a resource like:
https://api.twitter.com/1/statuses/home_timeline.json?callback=jQuery17107030615725088865_1341786299930&oauth_nonce=15094349&oauth_timestamp=1341785696&oauth_consumer_key=[OAUTH_CONSUMER_KEY HERE]&oauth_signature_method=HMAC-SHA1&oauth_version=1.0&oauth_token=[OAUTH_TOKEN HERE]0&oauth_signature=pQwHlKmepgtym%2Ffj%2BupCGP8mv3s%3D&page=2&include_entities=true&_=1341786306712
Still I get a 401 Unauthorized error. I checked the code three times so am wondering if I missing something???
Thanks.
For requests which requires an authentication, you have to put the authentication parameters in a HTTP header called Authorization, not in the POST parameters. It is explained in the Twitter API documentation here : https://dev.twitter.com/docs/auth/authorizing-request.

Categories