Secure requests in Angular - angularjs

I'm learning Angular and i'm using a 3rd party hotel Api to make a live booking request.
The Api says send all request values within the POST body as application/x-www-form-urlencoded
Angular form
Should I use $httpParamSerializer or
$http.post(url, data,{headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
.success(function(response) {
// your code...
});
I have also read that a standard $http request will just send it as default json anyway and is not needed?
What is most secure way for sending from data?

Related

405 Error with POST request (AngularJS $http)

I want to do a post request on Google Contacts API with AngularJS $http.
I tried to do this :
var config = {
headers: {
// "Content-Type": "application/json",
"Authorization": "Bearer " + gapi.auth.getToken().access_token,
"GData-Version": "3.0"
}
}
var data = {
"test": "test"
}
$http.post('https://www.google.com/m8/feeds/contacts/default/full/', data, config);
But it returns "XMLHttpRequest cannot load https://www.google.com/m8/feeds/contacts/default/full/. Response for preflight has invalid HTTP status code 405"
This request is working (returns 201 created) on a RestClient like Postman.
If someone could explain to me why this method is not allowed from a browser.
I believe the issue is that the https://www.google.com/m8/feeds/contacts API simply doesn't support OPTIONS requests. The 405 response is essentially saying the endpoint doesn't support the OPTIONS request, not necessarily that it doesn't support POST.
The solution is to use Google's own JavaScript API library rather than Angular's $http service.
You can use the JavaScript client library to interact with Google APIs, such as People, Calendar, and Drive, from your web applications.
There's also some documentation on how Google's API library supports CORS requests.
There may be some Angular wrapped versions of this library to make your life a little easier however I haven't dug around.

How to communicate AngularJS's $http routes and APIs developed in C Programming

I have made web application GUI using AngularJS, Bootstrap, HTML, CSS.
Backend team are developing APIs in C Programing.
So how my routes in $http request (sending from factory) will communicate to C Programing API (Controller) to get data or to perform related operations.
Thanks!
You would just need the URI and the Async request would look like this:
$http.get('URI goes here').then(
function (response) {
//success
vm.data = response;
},
function (response) {
//fail
console.log("error");
}
);
I think you need to learn the concepts of Web API's. Basically the server (C written in your case?) responds to various HTTP requests (GET, POST, PUT, etc..). By defining a Web API you simply state that for some http request for a specific path - there's gonna be a meaningful response.
For example here's a Web API:
GET /api/users - list users
GET /api/users/{id} - get a specific user
POST /api/users/{id} - update specific user
To consume this endpoint (/api/users) you can use $resource or $http like so:
var UserFactory = $resource('/api/users/:id');
var userlist = UserFactory.query();
var user = UserFactory.get({id: 123});
user.$promise.then(function(){
user.balance = 100000000;
user.$save();
});
Basically in the background angular translates $resource calls to HTTP requests.

CROS OPTIONS request when trying to upload a file with $http angularjs

I'm actually trying to implement a file upload system between my client side angularjs app and my server but i'm having difficulties to implement this feature.
The problem seems to come from the preflight OPTIONS request sent from Chrome.
When I test my route with postman everything work just fine.
Here is a few screen shots of the postman request execution:
First part of postman example
Second part of postman example
As you can see the route has two parameters a library id and a file to be uploaded and an authentification token.
The problems appear when I try to implement an upload feature in my angular web app.Indeed when I call my $http post request a OPTIONS preflight request is sent to my server.This OPTIONS request doesn't seem to have any of the parameters given to the post request it precedes making my authentification middleware (that has the function of validating the user/token) on my server side respond with a 401 error.
More exactly:
XMLHttpRequest cannot load ..... Response for preflight has invalid http status code 401
It seems that those preflight request are made by the browser when say detect a cross origin resource sharing. This is were I hit a brick wall. I cannot seem to understand how to:
- either send the token with the options request to validate this request
- or to bypass this options request to directly send my post request.
my upload function looks like this:
$http({
method: 'POST',
url: 'my-upload-url',
headers: {
'Content-Type': 'multipart/form-data'
},
data: {
library: my-library-id,
file: my-file-to-upload,
token: user-authentification-token
},
transformRequest: function (data, headersGetter) {
var formData = new FormData();
angular.forEach(data, function (value, key) {
formData.append(key, value);
});
var headers = headersGetter();
delete headers['Content-Type'];
return formData;
}
})
.success(function (data) {
})
.error(function (data, status) {
});
My questions are:
Is there a way to actually send my user token in the OPTIONS request to make it valid server side?
Is there a way of formatting my post request (header/data/params) to make it bypass this preflight browser request?
Is the formatting of my post request wrong in any way making it trigger the OPTIONS request from Chrome?
Thank you in advance for your help.
Martin
In cors, the OPTIONS method is used to tell the server what will your request do. The server must handle the OPTIONS correctly so your main request will send normally. The browser will send the OPTIONS request automatically when your request is a complex cross origin request.
To bypass the OPTIONS request your request should be POST and GET and content-type must be application/x-www-form-urlencoded, multipart/form-data, or text/plain and the headers only contain Accept, Accept-Language and Content-Language.
Your request is not wrong. The reason is that your request is a cross origin request and it isn't a simple request.
So the best way to solve this problem is to make your server handle the cors request correctly.
For express you can use https://github.com/expressjs/cors
see more: cors-mdn cors-w3c

How to secure my authentication headers on Angularjs when accessing REST API

I have this angularjs code below to access an API in json format with OAuth2's token. But I noticed writing in this way the access token can be seen and captured by everyone. I wonder how to hide or secure this so that no one can get the token easily by just checking the source.
<script>
var app = angular.module('myApp', []);
app.controller('articleCtrl', function($scope, $http) {
$http({
url: "http://example.com/api/article",
method: "GET",
headers: {
"Authorization": "Bearer bVM1HTeZ5R0HETGSTdjeg",
},
}).success(function(response) {
$scope.items = response;
});
});
</script>
You should use a HTTPS/SSL protocol to stablish communication with your REST API
You'll need to communicate with the API on the serverside and send the results to the client. There is no other way. People will be able to view your sourcecode, it's sent to the client so it can be executed. At that point it's in the hands of your client and they have your key. You could obfuscate your sourcecode but if somebody wants to, it's easy to undo. Just do API calls on your serverside through PHP/Node or whatever you are running and send the results to your client. The client isn't able to read your serverside code so your key will be safe. So instead of: API <> Client you'll need to do API <> server <> client

Request changed from POST to OPTIONS hangs

I am trying to send a POST request to an endpoint over HTTPS.
The request has 2 headers, content-type (application/json) and an apiKey.
I am using the request in a PhoneGap application built in Angular, and when the request is sent its method is changed to OPTIONS.
I know this is standard practice for browsers due to CORS, but I have a payload which I need the server to take, and I'm told by the server guys that OPTIONS requests have an empty payload with CORS (although I can't find verification on this).
The server is set up for CORS and should accept POST and OPTIONS.
For some reason my request hangs.
Angular code:
var submitDBIDResource = $resource(env.loginUserUrl, {}, {
save: {
method: 'POST',
headers: { 'apiKey': apiKey }
}
});
submitDBIDResource.save({"dbid": dbid}).$promise.then(function(data) {
console.log(data);
return data;
});
I have in my config.xml file
Any ideas what I need to do?
Thanks
The browser will automatically send an OPTIONS request before it sends the POST request. The OPTIONS request must respond with the appropriate response or else the browser will not send the POST request.
Your backend guys need to create two request handlers, one for the OPTIONS and one for the POST.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

Resources