Angular http.post header issue - angularjs

How do I send CSRF and Token data in a http request?
I'm using Angular to post json data to a Drupal services endpoint but I'm experiencing problems.
// drupal post node
$scope.post_node = function(){
console.info('Node post ...');
var promise = $http.post('http://mysite/QuestionsGenerator/angularjs-headless/api/v1/node',
{
"title" : "Node Test",
"body" : "Node body contents test#2",
"type" : "page"
},
{
'Content-type' : 'application/json',
'Accept' : 'application/json',
'X-CSRF-Token' : $cookieStore.get('user_session_token'),
'Cookie' : $cookieStore.get('user_session_cookie')
}
)
.then(
// successCallback,
function(response){
console.log('Post-node working ...');
$log.info(response);
},
// errorCallback
function(response){
console.log('Post-node NOT working ...');
$log.error(response);
}
);
return promise;
}
}]);
Using the code above, I'm trying to post to a Drupal services endpoint for a node to be created - so I have to post a title, body and node type for the new node.
In addition, I have to post X-CSRF-Token and Cookie information which authenticates my Angular user with Drupal so the node can be successfully created.
However, I receive the following error: Refused to set unsafe header "Cookie" followed by a message which says the user is not logged in - I can confirm the user not only exist but is logged in.
My network tab shows no details of my token or cookie details begin sent - which would explain the user not begin authenticated.
How can I send my cookie and token data?
UPDATE
I tried adding the withcredentials line as in the code below:
var headlessQS = angular.module('headlessQS', ['ngRoute', 'ngCookies']);
headlessQS.config(function($routeProvider, $httpProvider){
$routeProvider
$httpProvider.defaults.withCredentials = true
.when('/', {
templateUrl: 'pages/main.html',
controller: 'mainController'
})
.when('/wiris', {
templateUrl: 'pages/wiris.html',
controller: 'wirisController'
})
.when('/signin', {
templateUrl: 'pages/signin.html',
controller: 'signinController'
})
});
// Controllers
......
But, I get the following error:
Uncaught Error: [$injector:modulerr] http://errors.angularjs.org/1.3.0-rc.2/$injector/modulerr?p0=headlessQS&p1=…
Also, when the withcredentials code does work, do I add my token etc data like in the following code:
var promise = $http.post('http://mysite/QuestionsGenerator/angularjs-headless/api/v1/node',
{
"title" : "Node Test",
"body" : "Node body contents test#2",
"type" : "page"
},
{
headers: {
'Content-type' : 'application/json',
'Accept' : 'application/json',
'X-CSRF-Token' : $cookieStore.get('user_session_token'),
'Cookie' : $cookieStore.get('user_session_cookie')
}
}
)
.then(
// successCallback

If you're using $cookies, and you set:
$httpProvider.defaults.withCredentials = true; // from main module
then your cookies should be sent on every request.
By default, $http will also read a token from an XSRF-TOKEN cookie and apply an X-XSRF-TOKEN header to the request.
If you're trying to send a JWT token as a Bearer token on the Authorization header, look into using an HTTP Interceptor:
// register the interceptor as a service
$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
return {
'request': function(config) {
var access_token = tokenService.getAccessToken();
if (access_token) {
if (config.url.indexOf(this.myAPIUrl) === 0) {
config.headers.Authorization = 'Bearer ' + access_token;
}
}
return config;
}
};
});
$httpProvider.interceptors.push('myHttpInterceptor');
Note: You can also use the HTTP Interceptor to capture all HTTP responses, and errors on HTTP requests and responses.

Related

AngularJS : Implementing token in $http

I am very new to angularJS.
My Backend is DRF and I have successfully implemented token.
this is my token:
{
"key": "217c3b5913b583a0dc3285e3521c58b4d7d88ce2"
}
Before I implement token in backend, it was working nice:
$scope.getAllContact = function() {
var data = $http.get("http://127.0.0.1:8000/api/v1/contact")
.then(function(response) {
$scope.contacts = response.data;
});
};
But, now I am not getting how can I implement this token here
Can anyone help me in this case?
Try to use this. You need to attach the token in the headers.
$http({
url : "http://127.0.0.1:8000/api/v1/contact",
method : 'GET',
headers : {
'Content-Type' : 'application/json',
'key': "217c3b5913b583a0dc3285e3521c58b4d7d88ce2"
}
}).then(function(response){
$scope.contacts = response.data;
});
Note that, this is binding the token to only this request. Use $http interceptors to add the token to each request that you make.
See here: Angular Js - set token on header default

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));
});
}

parse.com POST call from angularjs CORS error

I am using parse.com cloud code and has a function inside, which is called using a https post call from my angularjs.
When I test the same function from POSTMAN REST client it works.
But from my domain it gives a CORS error
XMLHttpRequest cannot load
https://api.parse.com/1/functions/sendemail. Response to preflight
request doesn't pass access control check: A wildcard '*' cannot be
used in the 'Access-Control-Allow-Origin' header when the credentials
flag is true. Origin 'http://www.crickify.com' is therefore not
allowed access.
Cloud Code:
Parse.Cloud.define("sendemail", function(request, response) {
//response.success("Hello world!");
var mailgun = require('mailgun');
console.log("from parselog",request.params);
response.set("Access-Control-Allow-Origin", "http://www.crickify.com");
response.set("Access-Control-Allow-Headers", "X-Requested-With");
response.set('Access-Control-Allow-Headers', 'Content-Type');
mailgun.initialize('XXX', 'XXX');
mailgun.sendEmail({
to: "bala#mindlens.com.sg",
from: "Mailgun#CloudCode.com",
subject: "Hello from Cloud Code!",
text: "Using Parse and Mailgun is great!"
}, {
success: function(httpResponse) {
console.log(httpResponse);
response.success("Email sent!");
},
error: function(httpResponse) {
console.error(httpResponse);
response.error(httpResponse);
}
});
});
Angular Code:
$scope.sendemail = function(passedEmail) {
// body...
var email = passedEmail;
var message = {mail:email};
$http({
method: 'POST',
url: 'https://[app key]:jskey]#api.parse.com/1/functions/sendemail',
data: message
})
.success(function(data) {
console.log("Success" + data);
})
.error(function(error) {
console.log("Success" + data);
});
}

Token authorization - Browser throws Login form

I am working on a token implementation into Angular/.Net application. My part is the front-end. What's happening is that when UI sends a request with the expired token and the server replies with 401 I cannot intercept that before the Browser raises the Login form. As the result I cannot send a request to refresh the token. Can someone please give me an idea how that is supposed be managed? I will provide code just don't know what's to show.
Thanks
Adding code:
var response = $http({
method: "GET",
dataType: "json",
params: params,
headers: {
'Content-Type': "application/xml; charset=utf-8",
},
url: someurl
});
response = response.then(function (data) {
return data.data;
});
response.catch(function (data) {
$q.reject(data);
});
// Return the promise to the controller
return response;
The problem is that I cannot redirect on UI because Browser throws Login form before my code is hit when the server returns 401.
Make ajax request, and if you get 401 then redirect to login page.
P.s. for better understanding provide your code how you implement ajax request. Which module do you use for front-end auth? I recommend satellizer
Added:
I guess you need the following configuration on angular
var app = angular.module('App', ['satellizer'])
.config(function() {
/* your config */
}
.run(function($rootScope, $location, $auth) {
// Check auth status on each routing,
// Redirect to login page, if user is not authenticated or if token expired
$rootScope.$on('$routeChangeStart', function(event, next, current) {
if (!$auth.isAuthenticated()) {
$location.path('/auth/login');
}
});
});

Authorization header in AngularJS not working

I am using the Django REST token authentication for my API.
I posted my credentials to obtain token endpoint. However when I try to set the header in a correct way it keeps responding with a http 401 error. I tried it using curl -X GET http://127.0.0.1:8000/events/ -H 'Authorization: Token 4d92d36768ca5d555b59cf68899eceab39c23704 ' and that does work! This is my code:
app.controller('HomeController', ['$scope','$http', function($scope,$http) {
$scope.username = '';
$scope.password = '';
$scope.submitLogin = function () {
var credentials = {
username : $scope.username,
password : $scope.password,
};
var req = $http.post('http://127.0.0.1:8000/api-token-auth/', credentials);
req.success(function(data, status, headers, config) {
$scope.token = data.token;
var str1 = 'Token ';
$scope.tokenheader = str1.concat($scope.token);
$http.defaults.headers.common.Authorization = $scope.tokenheader;
});
req.error(function(data, status, headers, config) {
alert( "failure message: " + JSON.stringify({data: data}));
});
};
$scope.getEvents = function () {
var req = {
method: 'GET',
url: 'http://127.0.0.1:8000/events/',
}
$http(req).then(
function() {
console.log('succes')
},
function(){
console.log('fail')
});
};
}]);
And the error message in chrome dev tools:
XMLHttpRequest cannot load http://127.0.0.1:8000/events/.
Response for preflight has invalid HTTP status code 401
How do I get rid of this 401 error?
Edit: I just found out the fault lies in the fact that I did not have CORS installed on my API. I was using a CORS plugin in chrome that worked for the authentication part of my api but not for my events url!
Did you check that the token is actually added to your request?
You can do this for example using the Chrome developers tools.
Personally I prefer to use the $httpprovider.interceptor as described in:
angularjs $httpProvider interceptor documentation
This ensures that the tokens are always present on any call.
If you are accessing more than one API, you should consider adding something like:
$httpProvider.interceptors.push(['$q', '$location', '$log', 'loginService', 'restHelperService',
function ($q, $location, $log, loginService, restHelperService) {
return {
request: function (config) {
// check if the request comes with an url
if (config.url) {
// check that the call is to the REST api, if yes add token
if (restHelperService.isRestCall(config.url)) {
// add auth header or revert to login
if (loginService.userIsLoggedIn()) {
config.headers = config.headers || {};
config.headers.Authorization = 'Token ' + loginService.getToken().token;
} else {
$location.path('/login');
}
}
}
return config;
},
responseError: function (response) {
if (response.status === 401 || response.status === 403) {
// clear auth token if the REST call failed with the current token
if (response.config && response.config.url && restHelperService.isRestCall(response.config.url)) {
$log.debug(" restCall failed due to bad credentials, resetting credentials");
loginService.resetCredentials();
$location.path('/login');
}
}
return $q.reject(response);
}
};
}]);
}])
This avoid issues that will arise when you start adding the token to API calls that don't expect them. Also the code ensures that a user will be automatically redirected to the login page if the credentials are not valid.
The example, I'm using two additional services. A loginService that manages the tokens and a restHelperService that manages the urls of the REST framework.
I would recommend doing the same as else it will be hard to access the credentials from outside your controller.
You need to add Token to the headers:
get($http, "/some_url", {headers: {"Authorization": "Token " + $your_token}}
....
....
);
Response code 401 means Unauthorized. If you are using Token based authentication then in case of fail it would be 403, Forbidden.
So my guess would be that it's username/password who is messing with it. In your curl example you are not using them.

Resources