Unable to send token from AngularJS to Laravel API - angularjs

This is how I am handling the process of sendig the csrf_token().
In the <head> section I added the token as a constant.
<script type="text/javascript">
var myApp = angular.module('myApp', ['ngRoute', 'ngSanitize', 'productController', 'productService'])
.constant("CSRF_TOKEN", '<?= csrf_token() ?>');
</script>
In the productService when I send post data, I include the following:
headers: {'Content-Type': 'multipart/x-www-form-urlencoded', 'X-XSRF-TOKEN': CSRF_TOKEN}
Then I receive from Laravel the error:
DecryptException: invalid data
If I remove X-XSRF-TOKEN from headers: above, then I receive the TokenMismatchException.
As suggested from another post, I encrypted the csrf_token(), since Laravel is expecting the token to be encrypted, but even then I still receive DecryptException: invalid data.

Changing X-XSRF-TOKEN to X-CSRF-TOKEN solved the problem.
When testing, I had to destroy the cookie and restart the browser for the token to kick in.

change XSRF to CSRF and restart your browser.

Related

angularJS $http CORS call handshake fails with TLS 1.2 bi directional in IE11

i created a hello world using angularJS 1.7 and running the webpage using http-server node module.
In the controller using $http service a CORS call is made.
CORS call is trying to establish a TLS 1.2 mutual authentication with an API. Certificates on both the server and the client are installed. When tested with Chrome initial handshake fails, but it gives a popup to select the certificate. once the certificate is selected the handshake is successful and data is retrieved.
Certificates are self signed added at root level.
However the same fails in IE11.
"Access-Control-Allow-Origin" is set to the client's IP.
below are wire shark logs.
Client send Hello
Server respond with Server hello and certificates.
However the server sends an alert to "Close Notify"
Wire shark handshake logs
rest error
The flag in the response say "Reset"
Below is the html code
<!DOCTYPE html>
<html>
<head>
<script src="angular.js"></script>
</head>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<p>Response log:</p>
<h1>{{myWelcome}}</h1>
<p> Status </p>
<h3> {{pstatus}} </h3>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http({
method: "POST",
url: 'https://serveraddress:portno/myrestapi/methodcall/',
headers: {
'Content-Type': 'application/json'
}
}).then(function(response) {
$scope.myWelcome = response.data;
}).catch(function(error){
$scope.myWelcome= error;
});
i havent found a similar article
IE is not sending Client certificate in TLS mutual authentication
however it didnt resolve the problem.
Any suggestion why the handshake is getting closed? any input?
Doew IE11 support this?
Thanks in advance.

Auth0 Authorization throws Unauthorized

I try to implement Auth0 in my Single-Page-App using angular.
here are the scripts i loaded for auth0:
<!-- Auth0's lock widget library -->
<script type="text/javascript" src="https://cdn.auth0.com/js/lock-9.0.js"></script>
<!-- Angular cookie wrapper library for client cookies -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular-cookies.js"></script>
<!-- Auth0's Angular SDK Library -->
<script type="text/javascript" src="https://cdn.auth0.com/w2/auth0-angular-4.js"></script>
<!-- Angular wrapper for localStorage and sessionStorage. Defaults to ng-cookies if not available -->
<script src="http://cdn.rawgit.com/auth0/angular-storage/master/dist/angular-storage.js" type="text/javascript"> </script>
<!-- Angular wrapper library for JWT-->
<script src="http://cdn.rawgit.com/auth0/angular-jwt/master/dist/angular-jwt.js" type="text/javascript"> </script>
But the Token has an invalid Signature and is always unauthorized when i try the api call for the user information here : Api to get user data
the token is stored in the local storage in the following eventhandler
authProvider.on('loginSuccess', ['$location', 'profilePromise', 'idToken', 'store',
function($location, profilePromise, idToken, store) {
profilePromise.then(function(profile) {
store.set('user', profile.email);
store.set('token', idToken);
});
$location.path('/');
}]);
The debugger from jwt.io always says invalid Signature when i try to decode my jwt even with my client secret.
Did i do something wrong ? Why is my token Signature invalid ? Why is my token unauthorized? Does the Api page even work on actual data ?
EDIT:
I found out that i used the wrong api call i used the one for auth0-access-tokens instead for JWTs.
But still the JWT Debugger shows invalid Signature
If you are using the idToken, you should be calling the /tokeninfo endpoint. Be sure to follow the required format: it should be a POST, with content type json containing this payload:
{
"id_token" : "[the token]"
}
However, you probably don't want to do any of this. The call to /tokeninfo will get you the user profile, but the SDK already does that for you after authenticating the user. The same user profile is available in the callback from profilePromise here:
authProvider.on('loginSuccess', ['$location', 'profilePromise', 'idToken', 'store',
function($location, profilePromise, idToken, store) {
profilePromise.then(function(profile) {
// 'profile' contains the same information that
// you would get calling '/tokeinfo' or '/userinfo'
// so consider storing the whole 'profile' instead
// of just 'profile.email'
store.set('user', profile.email);
store.set('token', idToken);
});
$location.path('/');
}]);

AngularJS $http wrong http status on error

I am trying to build a JSONP request with AngularJS's $http Service and on errors I am getting wrong http status code 404 instead of 500, and the body of the page is missing too.
So here is the scenario:
The URL I am calling returns a 500 Internal Server Error with a JSON output containing the error message:
http://private.peterbagi.de/jsfiddle/ng500status/api.php?code=500&callback=test
index.html
(see it in action: http://private.peterbagi.de/jsfiddle/ng500status/ )
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title></title>
<script src= "//ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.min.js"></script>
<script src= "app.js"></script>
</head>
<body ng-app="app" ng-controller="UploadController">
<button ng-click="upload(200)" value="OK">OK</button>
<button ng-click="upload(500)" value="Fail">Fail</button>
<pre>{{response | json}}</pre>
</body>
</html>
app.js
var app = angular.module('app', []);
app.constant('BASE_URL','http://private.peterbagi.de/jsfiddle/ng500status/');
app.controller("UploadController", ['$scope','Upload','BASE_URL',
function($scope,Upload,BASE_URL) {
$scope.upload = function(code) {
Upload(code).then( function(response) {
$scope.response = response;
}, function(error) {
$scope.response = error;
} );
}
}]);
app.factory('Upload', ['$http','BASE_URL', function($http,BASE_URL) {
return function (code) {
var callUrl = BASE_URL + "api.php?code="+code;
return $http({
method: 'JSONP',
url : callUrl+"&callback=JSON_CALLBACK"
});
}
}]);
When you click on the Fail button the returned status is 404 and the
response body is missing too.
output
{
"status": 404,
"config": {
"method": "JSONP",
"transformRequest": [
null
],
"transformResponse": [
null
],
"url": "http://private.peterbagi.de/jsfiddle/ng500status/api.php?code=500&callback=JSON_CALLBACK",
"headers": {
"Accept": "application/json, text/plain, */*"
}
},
"statusText": "error"
}
In Chrome DevTools Network panel you see the correct response code (500) and I would expect to see the same result in the Angular output.
Why is this happening or what am I doing wrong?
Update:
I built the a similar example, but with GET-Requests instead of JSONP and it works well: http://private.peterbagi.de/jsfiddle/ng500status2/
It seems to be a JSONP specific problem. Nevertheless it doesn't solve my initial problem, because I have to work with Cross-Domain Requests. Any ideas?
According to the angular source's httpBackend.js line 63 and line 190,
the status of a 'JSONP' request can only be -1, 404, or 200.
The reason is that in angular 'JSONP' request is not an XMLHttpRequest. AFAIK there is no way to handle the specific error code in this way. The only thing javascript know is whether this request succeeded.
UPDATE:
Here in my answer above:
the status of a 'JSONP' request can only be -1, 404, or 200.
This means the status given by angular for the response of this request.
XMLHttpRequest is the standard request type we normally used in ajax.It sends request to the server and fetch the response so you can see the HTTP status code(200,404,500,401,etc.) given by the server side.
However, it has limits like in most cases you cannot make a cross-domain XMLHttpRequest (unless you've set up the allow-cross-domain header on the server side).
In this way we need JSONP to help us make cross-domain requests. In fact 'jsonp' is appending <script> tags to your document (which are always removed when request finished) whose src attributes are the URLs you given.
In angular, listeners are added to this <script> to track the status of the request. However, these listeners can only tell whether the script is loaded successfully. If it succeeded, angular set the status of your response to 200. If not, 404 is assigned. That is why the status field is either 404 or 200, regardless of what the server actually gives.

No 'Access-Control-Allow-Origin' error from local domain to public API

I'm trying to create an app that will retrieve the stock name, asking and buy price from Yahoo Finance API, using Restangular. I'm having a problem with accessing a public API in the local application I'm creating when I do a GET request. This is the URL with parameters that I'm sending:
http://finance.yahoo.com/d/quotes.csv?s=MSFT+GE&f=nab
Using Postman, this get request returns an array which contains the stock name, asking price and buy price of the stock. Doing the request in postman returns the desired information without any errors.
When I do this request in my local, I get the following error:
XMLHttpRequest cannot load http://finance.yahoo.com/d/quotes.csv?s=MSFT+GE&f=nab. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.
The HTML code is as follows:
<html ng-app="app">
<head>
<title>Restangular</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script src="//code.angularjs.org/1.2.27/angular-resource.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js"></script>
<script src="//cdn.rawgit.com/mgonto/restangular/master/dist/restangular.min.js"></script>
</head>
<body>
<div ng-controller="IndexCtrl" ng-cloak>
<ul>
<li ng-repeat="person in people">{{person.Name}}</li>
</ul>
</div>
And the JS:
var app = angular.module('app', ['restangular'])
.config(function(RestangularProvider) {
RestangularProvider.setBaseUrl('http://finance.yahoo.com/d');
});
app.controller('IndexCtrl', function($scope, Restangular) {
$scope.people = Restangular.all('quotes.csv?s=MSFT+GE&f=nab').getList();
});
I'm confused by this error because since this is a public API and POSTMAN can access it, I'd assume that the header is already present in the API server. Why would I get this error when requesting from my local?
Any help would be GREATLY appreciated.
Here's me making a JSONP request which fails because it's trying to receive a CSV file. I don't think restangular knows how to read CSV files either which is what you are attempting. I think you need to do the same thing as you are now but using the YQL API instead because I don't think this is going to work.
Anyway here's the code:
http://plnkr.co/edit/GokYqzJ0dXw86C6AM2UP?p=preview
The request (which goes through but fails due to the file type):
app.controller('MainCtrl', function($scope, $http) {
$scope.name = 'World';
$http.jsonp('http://finance.yahoo.com/d/quotes.csv', {
params: {
callback: 'JSON_CALLBACK',
s: 'MSFT GE',
f: 'nab'
}
}).success(function(response) {
console.log(response);
}).catch(function(response) {
console.log(response);
})
});

Can't perform CORS request using Angularjs

I am writing my first AngularJS app and have run into a problem with CORS in Angular. Have tried what was mentioned in this reply but still have no luck solving this.
The JS code (main.js) is as follows:
var app = angular.module("app",[]);
app.config(['$httpProvider', function($httpProvider) {
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
]);
app.controller("AppCtrl", function ($scope, $http) {
var postData = "username=demo&password=demo";
$http.post("http://sampleurl.com/login",postData).success(function(data, status, headers, config)
{
console.log(data);
});
});
The Index.html file is:
<!DOCTYPE html>
<html>
<head>
<title>Sample Angular App</title>
</head>
<body ng-app="app" ng-controller="AppCtrl as app">
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.7/angular.min.js"></script>
<script src="main.js"></script>
</body>
</html>
The error I get is the following:
Failed to load resource: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
I have tried running this request using Ajax and it works just fine with Ajax. For some reason can't get this to work using Angular. Any idea as to what I am doing wrong here?
Thanks!
Ok. So basically after alot of tinkering around I realised that params were not getting passed using
$http.post("http://sampleurl.com/login",postData)
So I rewrote this request as follows:
$http({
url:'http://sampleurl.com/api',
method:"POST",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: postData
})
This got the request to go through just fine. Hope this is of help to someone else.
Cheers!
There are two things you will need to do, in the .config you need to put this:
$httpProvider.defaults.withCredentials = true;
And then on your server you need to return an an Access-Control-Allow-Origin header, it would possibly look like this:
Access-Control-Allow-Origin:http://URL_OF_SITE_YOUR_ANGULARJS_APP_IS_AT
If you want to send a CORS request 'withCredentials', you'll need to have your server reply with 'Access-Control-Allow-Origin':'http(s)://your.request.origin'. A wildcard (*) reply will be refused by most browsers for requests with credentials.
I was stuck with the same issue, then I read from this link:
http://better-inter.net/enabling-cors-in-angular-js/
and things worked like a charm :)
var myApp = angular.module('myApp', [
'myAppApiService']);
myApp.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
]);
I had the same problem before and I resolve it by adding this header:
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},

Resources