Mailgun + AngularJS + Auhtentication for http post request - angularjs

I am trying to convert below sample code in angular request.
https://documentation.mailgun.com/user_manual.html#sending-via-api
curl -s --user 'api:YOUR_API_KEY' \
https://api.mailgun.net/v3/YOUR_DOMAIN_NAME/messages \
-F from='Excited User <mailgun#YOUR_DOMAIN_NAME>' \
-F to=YOU#YOUR_DOMAIN_NAME \
-F to=bar#example.com \
-F subject='Hello' \
-F text='Testing some Mailgun awesomness!'
I have tried below with Authorization headers which still comes back with Unauthorized error. I see request header has authorization field set with value.
What am I doing wrong?
var url = "https://api.mailgun.net/v3/sandboxXXXXXXXXXXXXXXXXX.mailgun.org/messages";
var dataFields = {
to: "verified recepient",
subject: "subject",
text: "text",
from: "postmaster address of sandbox domain"
}
var req = {
method : 'POST',
url: url,
headers : {
'Authorization' : 'Basic api:key-XXXXXXXXXXXXXXXX'
},
data: dataFields
}
$http(req).then(function(data){
console.log(data);
}, function(data){
console.log(data);
})

Finally got it working from local machine - collective information from different post and using this plugin - https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi - I was able to make it work. So what does this plugin does? can I do this in my post request?
Without that it gives me error
XMLHttpRequest cannot load https://api.mailgun.net/v3/sandboxXXXXXXXXXX.mailgun.org/messages. Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.
var url = "https://api.mailgun.net/v3/sandboxXXXXXXXXXXXXXXX.mailgun.org/messages";
var dataJSON = {
from: "postmaster#sandboxXXXXXXXXXXXXXXX.mailgun.org",
to: "registered recepient",
subject: "Subject text",
text: "Body text",
multipart: true
}
var req = {
method : 'POST',
url: url,
headers : {
'content-type': 'application/x-www-form-urlencoded',
'Authorization': 'Basic ' + $base64.encode('api:key-XXXXXXXXXXXXX')
},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: dataJSON
}
$http(req).then(function(data){
console.log(data);
}, function(data){
console.log(data);
})
Things which I was missing.
Multipart
context type
encodedURIComponent - for parameters
base64 encoded api key

Try to add
username: 'api',
password: 'yourapikey',
in your header request

Related

Napster API Auth - BAD Request / Unauthorized

I am coding in Reactjs and trying to Auth/Outh into the Napster Web API, followed the information on this page: https://developer.napster.com/api/v2.2#authentication
A sample of my current code:
const API_KEY = 'OWIxMjhlY2MtOTA3Yi00NWJiLThiYTktODc3OTNiYTQ4MGU4';
const API_KEY_SECRET = 'OWIxMjhlY2MtOTA3Yi00NWJiLThiYTktODc3OTNiYTQ4MGU4';
url: 'https://api.napster.com/oauth/access_token',
method: 'post',
params: {
client_id: API_KEY,
client_secret: API_KEY_SECRET
},
headers: {
'Accept':'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Bearer ' + (new Buffer(API_KEY + ':' + API_KEY_SECRET).toString('base64'))
},
data: querystring.stringify({ grant_type: 'authorization_code' })
Response Payload:
{"code":"UnauthorizedError","message":"Authentication code not valid"}
{"code":"BadRequestError","message":"Invalid grant_type parameter"}
According to the documentation and sample below....
curl -v -X POST -d "client_id={api_key}&client_secret={api_secret}&response_type=code&grant_type=authorization_code&redirect_uri={redirect_uri}&code={temporary_code}" "https://api.napster.com/oauth/access_token"
...You don't need to send Authorization headers. It's a normal form post with all the parameters. So If you include the rest of the parameters along with client_id : API_KEY... it should do the trick.

CORS error while sending request from Browser to play server even after sending CORS header

I have a REST API developed using Play Framework/Java and front end developed in Angular JS.
I am trying to call a POST method fron the Angular Client to the server using the following code:
$scope.login = function () {
console.log('login called');
var loginURL = 'http://localhost:9000/login';
var loginInfo = {
'email': $scope.email,
'password': $scope.password
};
$http({
url: loginURL,
method: 'POST',
data: loginInfo,
headers: { 'Content-Type': 'application/json' }
}).then(function (response) {
console.log('SUCCESS: ' + JSON.stringify(response));
$scope.greeting = response.status;
}, function (response) {
console.log('ERROR: ' + JSON.stringify(response));
});
}
This is the code at my server:
public Result doLogin() {
ObjectNode result = Json.newObject();
result.put("status", "success");
return ok(result).withHeader("Access-Control-Allow-Origin", "*");
}
And this is the application conf file:
#allow all hosts.
play.filter.hosts {
allowed = ["."]
}
#allow CORS requests.
play.filters.cors {
allowedOrigins = ["*"]
}
Yet even after enabling CORS, I am getting error in console in both Firefox and Google Chrome:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:9000/login. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
ERROR: {"data":null,"status":-1,"config":{"method":"POST","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"http://localhost:9000/login","data":{"email":"xxx","password":"xxx"},"headers":{"Content-Type":"application/json","Accept":"application/json, text/plain, /"}},"statusText":""}
I do know that the server is sending the correct response and the correct header because when I do the POST from Postman, I can see the response and also the headers containing {"Access-Control-Allow-Origin", "*"} in Postman.
So then, what could be the problem? Is there something I am missing from the Client side?
The difference between POSTMAN request and browser request is browser sends an OPTIONS request before the actual POST / GET request.
To be able to accept OPTION request with your play framework allowedHttpMethods = ["GET", "POST" ,"OPTIONS"]
for follow this link
Play Framework 2.3 - CORS Headers
This causes a problem accessing CORS request from a framework (like angularjs). It becomes difficult or the framework to find what was the options request for and take action properly.
For fixing your problem you will need to analyze how the options request going and how it's being interpreted and how to overcome. But in general, I suggest using "fetch" built-in request for this, which supports the promises so can be chained easily with angularjs code
so your code will look something like this
$scope.login = function () {
console.log('login called');
var loginURL = 'http://localhost:9000/login';
var loginInfo = {
'email': $scope.email,
'password': $scope.password
};
fetch(loginURL, {
method: 'post',
headers: {
"Content-type": "application/json"
},
body: loginInfo
}).then(function (response) {
console.log('SUCCESS: ' + JSON.stringify(response));
$scope.greeting = response.status;
}, function (response) {
console.log('ERROR: ' + JSON.stringify(response));
});
}

Basic authenticiation in $http Get request

I am trying to access a REST API service with basic authenticiation.
This works perfectly as a curl request:
curl -D- -X GET -H "Authorization: Basic eW**********0NQ==" -H "Content-Type: application/json" "https://api.domain.com/api/users/email/first.last#domain.com"
In angular, I tried this and it does not seem to work as I get a 501 error...
var _url = "https://api.domain.com/api/users/email/first.last#domain.com";
var _authdata = Base64.encode('MyUsername' + ':' + 'MyPassword');
var _headers = {
'Authorization': 'Basic eWd***********0NQ==',
'Content-Type': 'application/json'
};
$http({
method: 'GET',
url: _url,
headers: _headers
}).then(function(request) {
console.log('request');
});
I am trying to understand why this isn't working out properly. CORS are not the problem...
Any suggestions ?
Base64.encode is not understandable by angular-js either you can use javascript "btao" and "atob" or you can include the base64 through npm
Maybe the following code snippet will help you.
var _url = "https://api.domain.com/api/users/email/first.last#domain.com";
var _authdata = btoa('MyUsername' + ':' + 'MyPassword');
var _headers = {
'Authorization': 'Basic' + _authdata,
'Content-Type': 'application/json'
};
$http({
method: 'GET',
url: _url,
json: true,
headers: _headers
}).then(function(request) {
console.log('request');
});
or you can include the Angular-base64 dependency using npm:
https://www.npmjs.com/package/angular-base64

Adding content-type header to Angular $http request

I'm trying to send HTTP request using the following code:
var editCompanyUrl = 'http://X.X.X.X:YYYY/editCompany';
var userId = localStorage.getItem("UserId");
var token = localStorage.getItem("Token");
var companyId = localStorage.getItem("companyId");
return $http({
method: 'POST',
url: editCompanyUrl,
params: {
token: token,
userId: userId,
companyId: companyId,
companyName: $scope.companyName,
},
timeout: 500
}).then(function (data) {
console.log(data);
//Store Company ID which is used for saving purposes
//localStorage.setItem("companyId", data.data.Company.id);
return data.data.Company;
}, function (data) {
console.log(data);
})
and handler of the request on the server side accepts requests with Content-Type: multipart/form-data. How can I add this content type to the request? I've tried many advices and tips from tutorials but no success. Could you please help me? In addition to it - what should I do when I will add a file with an image to this request? Can I just add it as additional parameter of the request?
Thank you very much!
Angular POST must be like below code.
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': undefined
},
data: { test: 'test' }
}
it should have data:{ }
so try to put your params: inside the data and it should work.

AngularJs $http.post -> Error: Unexpected Request POST ; no more request expected

I've got a working curl request here:
curl -u testclient:testpass http://mybackend.somedomain.com/token.php -d 'grant_type=client_credentials'
Now I try to translate this to my angularJs (ionicframework) frontend.
(The php-backend is on a different server, so this might maybe have something to do with CORS, too, though I don't know how)
In my frontend I try:
var username = 'testclient';
var password = 'testpass';
var url = 'http://mybackend.somedomain.com/token.php';
var request = $http({
method: "post",
url: url,
data: {
username: username,
password: password
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
This results in something weird, the POST request isn't executed, but instead I get the error message:
Error: Unexpected request: POST http://mybackend.somedomain.com/token.php No more request expected
What am I doing wrong here ?
There is a mistake in your Angular POST, your data is encoded as JSON instead of what you claim in headers application/x-www-form-urlencoded. First you should change your code to below.
$http({
method: 'POST',
url: url,
data: $.param({
username: username,
password: password
}),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
})

Resources