How to send my data in headers in post request .? - angularjs

I want to send my data in headers, so I converted my data into base64 and I'm getting the output in $http.defaults.headers.common['Authorization']. But how to post the basic auth data in headers in the post request
.factory('Auth', function (Base64,$http, AuthToken) { //for login/logout
var authFactory = {};
authFactory.login = function (loginData) {
var authdata = Base64.encode(loginData.username + ':' + loginData.password);
var userData = {
username: loginData.username ,
authdata: authdata
}
$http.defaults.headers.common['Authorization'] = 'Basic ' + authdata;
return $http.post('http://cc92e1dd.ngrok.io/api/authenticate',{'Authorization':'Basic ' + authdata})//is this correct format to send?
.then(function (data) {
AuthToken.setToken(data.data.token);
return data;
});
};

Something like below, just put you params into headers:
$http.get(url,
{ headers: {
'Cache-Control' : 'public',
'Pragma': '',
'Accept-Encoding':
'gzip, deflate, br',
'Authorization': 'Basic ' + authdata
}
});

Related

React Axios PUT authentication asks for infinite loop

For GET request the authentication working well, but when I am trying an authentication on PUT and POST requests it asks the USERNAME and PASSWORD for infinite times.
I written an authentication code for both GET and PUT but I am unable to understand why it s happening.
Please help me.
Here my GET request code:
var session_url = '';
var username = '';
var password = '';
var basicAuth = 'Basic ' + btoa(username + ':' + password);
axios.get(session_url, {}, {
headers: {
"Authorization": + basicAuth,
"Accept": "application/json",
"Content-Type": "application/json"
}
}).then((getData) => {
console.log(getData.data);
setApiData(getData.data);
}).then(function(response) {
console.log('Authenticated');
}).catch(function(error) {
console.log('Error on Authentication');
});
Here my PUT request code:
var session_url = '';
var username = '';
var password = '';
var basicAuth = 'Basic ' + btoa(username + ':' + password);
axios.put(session_url, {}, {
headers: {
"Authorization": + basicAuth,
"Accept": "application/json",
"Content-Type": "application/json"
},
"parameters":{
"Name":name,
"Email":email
}
}).then(function(response) {
console.log('Authenticated');
alert("success");
}).catch(function(error) {
console.log('Error on Authentication');
});
"parameters" is the data in my json file.
Here my json file formate fetching from the API (This not an actual data, its just a formate of a json data)
[{"parameters":{"Name":"abc","Email":"abc#gmail.com"}}]
We have to pass body value in data parameters. Please try it.
axios.put(session_url, {}, {
headers: {
"Authorization": + basicAuth,
"Accept": "application/json",
"Content-Type": "application/json"
},
data:{
Name:name,
Email:email
},
})
for more reference check this https://stackabuse.com/how-to-make-put-http-request-with-axios/

AngularJS 406 not acceptable http post request

I have a problem with a Post query that I use for a form. I get a "406 not acceptable" error every time I try to validate my form, and Object.data is blank..
var edit = function(form){
var token = window.localStorage.getItem('token');
$ionicLoading.show();
return $http({
method : 'POST',
url : API.url + '/user',
headers : {Authorization : 'Bearer ' + token},
transformRequest: function(data, headers){
console.log(headers);
headers = angular.extend({}, headers, {'Content-Type': 'application/json;charset=UTF-8'});
console.log(headers);
console.log(data);
console.log(angular.toJson(data));
return angular.toJson(data); // this will go in the body request
},
data : form
}).then(function(result) {
console.dir(result.data);
},function errorCallback(response) {
console.log(response);
});
};
I I do not understand why it does not accept..
You should to send a json data to your server
try this following code by adding 'Accept': 'application/json, */*' to your header:
var edit = function(form){
var token = window.localStorage.getItem('token');
$ionicLoading.show();
return $http({
method : 'POST',
url : API.url + '/user',
headers : {
Authorization : 'Bearer ' + token,
'Accept': 'application/json, */*'
},
transformRequest: function(data, headers){
console.log(headers);
headers = angular.extend({}, headers, {'Content-Type': 'application/json;charset=UTF-8'});
console.log(headers);
console.log(data);
console.log(angular.toJson(data));
return angular.toJson(data); // this will go in the body request
},
data : form
}).then(function(result) {
console.dir(result.data);
},function errorCallback(response) {
console.log(response);
});

Basic authentication using http$ in Angular - Passing Username/Password and grant_type

I am trying to use Angular to authenticate against an authorization endpoint that I know works using Postman.
<script type="text/javascript">
var tokenGeneratorApp = angular.module('myApp', []);
myApp.controller('AuthenticationController', function ($scope, $http) {
var ac = this;
ac.authorizationToken = null;
ac.getAuthorizationToken = function () {
$http({
method : 'POST',
url: 'https://api.myserver.net/oauth/token',
data: {
grant_type: 'password',
username: 'theUserName',
password: 'thePassword'
},
headers: {
'Content-Type': 'application/json'
}
}).then(_authenticationSuccess, _authenticationError);
};
// Private methods to handle promise results
function _authenticationSuccess(response) {
ac.authorizationToken = response.data;
ac.resultsDisplay = ac.authorizationToken;
};
function _authenticationError(response) {
ac.resultsDisplay = 'An error occured: ' + response.data;
};
});
</script>
When I call getAuthorizationToken()I get an Http 400 back. When I look into the response.data object there is an error saying error:"unsupported_grant_type". This is confusing to me because in the Postman client I specify that the grant_type as password and all works as expected.
I must be doing something wrong in the Angular code.
Had a very similar problem recently. Try removing the 'headers' and insert 'dataType' instead, as follows:
$http({
method : 'POST',
url: 'https://api.myserver.net/oauth/token',
dataType: "json",
data: {
grant_type: 'password',
username: 'theUserName',
password: 'thePassword'
}
EDIT
$http({
method : 'POST',
url: 'https://api.myserver.net/oauth/token',
data: {
"username=" + theUserName + "&password=" +
thePassword + "&grant_type=thePassword"
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
//resolving => error:"unsupported_grant_type"
vm.BtnLogin = function () {
$scope.txtUsernamee;
$scope.txtPasswordd;
var client_credentials = $scope.txtUsernamee + $scope.txtPasswordd;
var auth = 'username=' + $scope.txtUsernamee + '&' + 'password=' + $scope.txtPasswordd + '&grant_type=password';
$http({
method: "POST",
url: '/token',
contentType: 'application/json',
data: auth
}).then(function success(response) {
//$('#successModal').modal('show');
console.log("ok")
},
function error(e) {
console.log(e)
}
);
};

Angularjs making post request to server. How to add key and value in angularjs using HTTP.POST. (ERROR : (POST http://IP/URL/ 403 (Forbidden)))

I am beginner programming with Angularjs and I want to make post request to my server. On the server side I'am waiting data with key value pair. I would like to know how to add the key and value in the HTTP.post.
Additional info:
XAMP &
Using CodeIgniter for the API.
This is what I have for the controller.
// calling our submit function.
$scope.submitForm = function() {
// Posting data to php file
var data = ({
'username': $scope.username,
'password': $scope.password,
'email': $scope.email,
'fName': $scope.firstName,
'lName': $scope.lastName,
'gender': $scope.gender
});
var config = {
headers : {
'Content-Type': 'application/x-www-form-urlencoded'
}
}
$http.post('http://IP/URL/ ', data, config)
.success(function (data, status, headers, config) {
$scope.PostDataResponse = data;
})
.error(function (data, status, header, config) {
$scope.ResponseDetails = "Data: " + data +
"<hr />status: " + status +
"<hr />headers: " + header +
"<hr />config: " + config;
});
};
When I submit the data, this is what I get.
CONSOLE ERROR :
http://i.stack.imgur.com/Qh8Ci.jpg
Network Preview information :
"http://i.stack.imgur.com/oKtM4.jpg
The solution to my problem was
1) Modify the code to this
function ($scope, $http, $stateParams, $httpParamSerializerJQLike) {
$scope.data = {}
// calling our submit function.
$scope.submitForm = function() {
// Posting data to php file
$http({
url: url,
method: 'POST',
data: $httpParamSerializerJQLike($scope.data),//
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'X-API-KEY' : '123456'
}
}) .success(function (data, status, headers, config) {
$scope.PostDataResponse = data;
})
.error(function (data, status, header, config) {
$scope.ResponseDetails = "Data: " + data +
"<hr />status: " + status +
"<hr />headers: " + header +
"<hr />config: " + config;
});
};
I modified the above code, thanks to this link/post that Mike provided to me.
( How do I POST urlencoded form data with $http in AngularJS? )
2) I Change the headers to this
headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'X-API-KEY' : 'PASSWORD' })
3) Implement this to the rest_controller in the API (Server side)
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With,
Content-Type, Accept, Access-Control-Request-Method");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
$method = $_SERVER['REQUEST_METHOD'];
if($method == "OPTIONS") {
die();
}

Converting ajax api post to $http post in angular js getting a 404

I'm trying to create a chat app where you can log into the incontact chat api (discard the weatherApp naming.. ).
This is the API documentation for the incontact chat api:
function startAgentSession() {
var startSessionPayload = {
'stationId': 'string',
'stationPhoneNumber': 'string',
'inactivityTimeout': 'integer - 30-300, or 0 for default',
'inactivityForceLogout': 'boolean',
'asAgentId': 'integer'
}
$.ajax({
//The baseURI variable is created by the result.base_server_base_uri
//which is returned when getting a token and should be used to create the URL base
'url': baseURI + 'services/{version}/agent-sessions',
'type': 'POST',
'headers': {
//Use access_token previously retrieved from inContact token service
'Authorization': 'bearer ' + accessToken,
'content-Type': 'application/json'
},
'data': JSON.stringify(startSessionPayload),
'success': function (result) {
//Process success actions
return result;
},
'error': function (XMLHttpRequest, textStatus, errorThrown) {
//Process error actions
return false;
}
});
``}
This is my attempt to convert in angular js, but for some reason I keep getting a 404, however, I'm at a loss for what I've done wrong..
weatherApp.controller('launchedController', ['$scope', '$http', '$document', function ($scope, $http, $document) {
$scope.clientResult = {};
$document.ready(function () {
var query_string = {};
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0; i < vars.length; i++) {
var pair = vars[i].split("=");
query_string[pair[0]] = pair[1];
}
if (typeof(query_string.access_token) != "undefined") {
var result = {};
result.state = query_string.state;
result.scope = query_string.scope;
result.access_token = query_string.access_token;
result.expires_in = query_string.expires_in;
result.resource_server_base_uri = query_string.resource_server_base_uri;
result.token_type = query_string.token_type;
}
$scope.clientResult = result;
});
console.log($scope.clientResult);
$scope.startSessionPayload = {
'stationPhoneNumber': '55555555555',
'inactivityTimeout': '0',
'inactivityForceLogout': 'false'
};
$http({
url: JSON.stringify($scope.clientResult.resource_server_base_uri) + '/services/v6.0/agent-sessions',
method: "POST",
headers:{'Authorization': 'bearer ' + $scope.clientResult.access_token,'content-Type': 'application/json'},
data: JSON.stringify($scope.startSessionPayload)
}).success(function(data) {
$scope.data = data;
consoloe.log('data', $scope.data)
}).error(function(status) {
$scope.status = status;
});
}]);
400 error is bad request. My guess is
replace
{
url: JSON.stringify($scope.clientResult.resource_server_base_uri) + '/services/v6.0/agent-sessions',
method: "POST",
headers:{'Authorization': 'bearer ' + $scope.clientResult.access_token,'content-Type': 'application/json'},
data: JSON.stringify($scope.startSessionPayload)
}
with
{
url: JSON.stringify($scope.clientResult.resource_server_base_uri) + '/services/v6.0/agent-sessions',
method: "POST",
headers:{'Authorization': 'bearer ' + $scope.clientResult.access_token,'content-Type': 'application/json'},
data: $scope.startSessionPayload
}

Resources