How to simulate curl command with Angular - angularjs

I have this curl command that I would like to simulate with angular:
curl -k -F fieldName=#data.json -u username:Password url
At the moment I went about doing an angular post. However, I run into the problem of authentication. There is no parameter for me to put the user id and password.
Angular code:
$scope.postCall = function () {
$scope.ngResult = "clicked";
var paramsJson = {
"imessageIdT": $scope.messageIdT,
"ilobT": $scope.lobT,
"iregionIdT": $scope.regionIdT,
"iassetClassT": $scope.assetClassT,
"additionalInfoT": $scope.additionalInfoT
};
var config = {
paramsJson: paramsJson
};
$http.post("WEBSITE", paramsJson, config)
.success(function (data, status, headers, config)
{
$scope.ngResult = logResult("POST SUCCESS", data, status, headers, config);
//$scope.ngResult = "Yes";
})
.error(function (data, status, headers, config)
{
$scope.ngResult = logResult("POST ERROR", data, status, headers, config);
//$scope.ngResult = "No";
});
};

Assuming basic authentication, not tested, this might work:
var username = "...", password = "***";
var config = {
headers: {
Authorization: "Basic " + window.btoa(username+":"+password)
},
method: "get", // or "post",
url: "destination.com"
};
$http(config).success(function(){
// on success
}).error(function(){
// on failure
});
The only thing I'm not certain about is window.btoa, if it's an RFC2045-MIME compliant variant of Base64, then you're good.
But my example is an over-simplification. Essentially, you should determine the authentication scheme supported by the server. It could be any one the following specified by IANA:
Basic
Bearer
Digest
HOBA
Negotiate
OAuth
Depending on the required scheme, you should compose the request header accordingly.

This depends on the api you are connecting to. Usually you would log and the server will return you an authentication token on the headers of the response.
1 Basic auth Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
2 Aoth2 Authorization: Bearer mF_9.B5f-4.1JqM
So you will need to add this header to your request:
$http.post("WEBSITE", paramsJson, angular.extend({}, config, {headers: {
'Authorization': token}}))
If the request is to another domain you should use jsonp.

Related

getting token as cookie from spring boot not accessible in angularjs

cookie does show in browser however cannot be accessed using $cookie.get('io'). What am I missing. I also tried $timeout with 5 seconds delay. I tried to see in headers() but this token does not show there.
Code:
$http({
url: 'http://localhost:8081/api/v1/login',
method: 'POST',
data: $httpParamSerializerJQLike({
username: username,
password: password,
REQUEST_TYPE: requestType
}), // Make sure to inject the service you choose to the controller
headers: {
'Content-Type': 'application/x-www-form-urlencoded' // Note the appropriate header
}
}).success(function (data, status, headers, config) {
//10 seconds delay
$timeout( function(){
var favoriteCookie = $cookies.get('io');
alert(favoriteCookie);
}, 5000 );
//time
var time = 0;
//timer callback
var timer = function() {
if( time < 5000 ) {
time += 1000;
$timeout(timer, 1000);
}
}
//run!!
$timeout(timer, 1000);
//console.log(response.headers('set-cookie'));
callback(response = { success: true });
}).error(function (data, status, headers, config) {
callback(response = { success: false });
});
Please check that the cookie you are trying to get is not tagged as httpOnly.
When you tag a cookie with the HttpOnly flag, it tells the browser
that this particular cookie should only be accessed by the server. Any
attempt to access the cookie from client script is strictly forbidden.
Of course, this presumes you have: A modern web browser. A browser
that actually implements HttpOnly correctly.
it was autogenerated cookie. the cookie which i was trying to access did not appear in the browser. I had to make some code modifications in angularjs to get the cookie into browser. I had to include a parameter "withCredentials:true," in the http request. As soon as I did it my cookie appeared in the browser. Now my http request look like this.
$http({
url: 'http:localhost/login',
method: 'POST',
data: $httpParamSerializerJQLike({
username: username,
password: password,
REQUEST_TYPE: requestType
}), // Make sure to inject the service you choose to the controller
withCredentials:true,
headers: {
'Content-Type': 'application/x-www-form-urlencoded;
}
}).success(function (data, status, headers, config) {
callback(response = { success: true });
}).error(function (data, status, headers, config) {
callback(response = { success: false });
});
}

Authorization failure with AWS API Gateway

I have integrated AWS API Gateway with AWS Cognito User pool. The following curl command works.
curl -X PUT -H "Authorization:<id token>" -d <json data> <https url>
However, authorization fails with the following Angularjs $http.put.
AWS cloudwatch logs show "user is unauthorized"
$http.defaults.headers.common['Authorization'] = token
$http.put('https://<url>', <json data> )
.then(function (data, status, headers, config) {
console.log('success')
}, function (data, status, headers, config) {
console.log('failure')
});
How should the authorization token be set with $http.put?
I think what you want to do is to set the header for the request as the second argument in the $http.put(<url>, options)....
So in your case, your code should look like this:
var options = {headers: {
'Authorization': token,
'Content-Type': 'application/json'
}
};
$http.put('https://<url>', <json data>, options);
You can check documentation here to learn more about different ways of invoking the $http.X methods.
I hope this helps.

"Must specify grant_type field" error when getting Oauth2 token

I've got a simple node.js backend build on Restify with OAuth2 authorization (restify-oauth2 plugin).
I've got a problem requesting a token. When I call POST method with my REST client, everything works correctly and I get access_token and token_type.
The problem occurs when I try to do the same thing in my frontend aplication made in Angular.
Here's my code:
var req = {
method: 'POST',
url: 'http://localhost:8080/token',
headers: headers,
data: {},
params: {grant_type: "client_credentials"}
};
$http(req).success(function(data, status, headers, config){
console.log('success');
}).error(function(data, status, headers, config){
console.log('error');
});
So as you can see, grant_type parameter is provided. But still the server responds with:
{"error":"invalid_request","error_description":"Must specify grant_type field."}
And here's devtools screenshot:
How do I need to change my request to make it work?
I finally solved it. The thing is that grant_type field must be passed inside a request body, not in the parameters.
Working request code:
var req = {
method: 'POST',
url: 'http://localhost:8080/token',
headers: headers,
data: "grant_type=client_credentials"
};
$http(req).success(function(data, status, headers, config){
console.log('success');
}).error(function(data, status, headers, config){
console.log('error');
});

Golang, cors and angularjs - header missing

I'm using rs/cors in my Go API to allow my Angularjs app to make direct requests. I've added the following code to configure CORS:
crs := cors.New(cors.Options{AllowCredentials: true})
n.Use(crs) //Negroni include
but I'm getting the No 'Access-Control-Allow-Origin' header is present on the requested resource message in the browser when I make a request.
My request looks like this:
var req = {
method: 'POST',
url: endPoint + version + method,
headers: {
'Authorization': 'Basic ' + btoa(':' + appId)
},
data: params
}
$http(req).
success(function(data, status, headers, config) {
callback(null, data);
}).
error(function(data, status, headers, config) {
callback(data);
});
How can I get round this?
Fixed it! I noticed that a few different headers were being sent with the request and I had to explicitly allow all of them.
AllowedHeaders: []string{"accept", "authorization", "content-type"}
I hope this helps someone.

AngularJS How to include header in Http request

I am new to angularjs. I am trying to make an API request that requires authorization. I have included it in the header of the request, but it is still not working. I am sure my access token is working. Any advice?
$scope.fetch = function() {
$scope.code = null;
$scope.response = null;
$http({
method: $scope.method,
url: $scope.url,
cache: $templateCache,
headers: {
Authorization: "access token"
}
}).
success(function(data, status) {
$scope.status = status;
$scope.data = data;
}).
error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
};
You could use following
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded;charset=utf-8";
It will add the above header to every POST call you make from your app. For adding a header common to all method, try following.
$http.defaults.headers.common['Authorization'] = "Bearer " + user.oauthInfo.access_token;
Do you see the header in your browser's network request log for the Request?
If so, is it in the expected format? Typically the "Authorization" header will have something before it, like "Basic " (as DevPat mentions in a comment above) or "Bearer ". What belongs here is dependent on the backend system receiving the request.
Examples of expected header:
Authorization: Bearer access_token
Authorization: Basic access_token

Resources