AngularJS : Implementing token in $http - angularjs

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

Related

Can't include header in `$http` angular

I got a token from backend which I saved it in $sessionStorage and I need to include that along with $http request that I call. I tried include it directly but when I checked it from backend, it's not there.
function _selectGender($sessionStorage, gender) {
return $http({
method: 'POST',
url: config.apiURL + '/auth/gender',
headers: {
'Authorization': $sessionStorage.token
},
data: {
gender: gender
}
}).then(updateCompleted).catch(updateFailed);
}
I also tried with interceptor which it's not working as well.
requestInterceptor.inject = ['$sessionStorage'];
function requestInterceptor($sessionStorage){
return {
'request': function(config){
if ($sessionStorage.token) config.headers['authorization'] = $sessionStorage.token;
return config;
}
}
}
Shoot me some idea how to tackle this. :D
Edit#1: It's likely possible to be preflight error
It's actually because of OPTIONS headers, seem like $http will send a pre-request before browser send an actual request to backend. You need to handle that from the backend. Thanks #Nitish Kumar's comment.
Read more about cors
How to handle OPTIONS

Angular http.post header issue

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.

Django JWT send token via Angularjs

how shall I send the token too access a view. Can I send it via POST or does it has to be via the header?
How can I send the token via header if that is necessary?
you have to send the token in the Authorization header. The token should be JWT <token>, as per documented in django jwt.
Here is the Angularjs based function I have written to show how to sign up, the code is very basic just for understanding you can write a separate service or factory, but for the sake of explaining this seems good.
$scope.registerUser = function(){
var postDict = $scope.user;
$http.post('http://127.0.0.1:8000/api/v1'+'/accounts/', postDict).success(function(data){
$scope.userRegistered = data;
var authData = {
username: data.username,
password: data.password
};
$http.post('http://127.0.0.1:8000/api-token-auth/', authData).success(function(data){
var token = data.token;
$http({
method : 'POST',
url : 'http://127.0.0.1:8000/api/v1/auth/login/',
data : authData, // pass in data as strings
headers : { "Content-Type": "application/json", "Authorization": "JWT "+data.token } // set the headers so angular passing info as form data (not request payload)
})
.success(function(data){
console.log(data);
var userdata = { "username": data.username, "first_name": data.first_name , "token": token , "last_name": data.last_name , "email": data.email};
$window.localStorage.setItem('userdata', JSON.stringify(userdata));
$state.go('app.dashboard');
});
});
});
}
now here we have obtained the token and in the headers property of the $http.post method of the angularjs, we have used this token for login.
This is how you can use Django JWT in Angularjs , also have a look at the django jwt documentation
You have to send it through a header named Authorization with the value: Token your-token-value.
In AngularJS you can do this through the $httpProvider in the configuration of your module, for instance:
angular.module('mymodule', []).config(function($httpProvider) {
$httpProvider.defaults.headers.common['Authorization'] = 'Token your-token-value';
});
After you do that, every request made with $http will have this header.

Attach parameter(s) with $http Angularjs

I have $http request in Angularjs project.
$http.get('http://api.domain.com/index?abc=123')
.success(function (data) {
console.log('Success!');
})
.error(function (data) {
console.log('False');
});
Now, i want add token to each $http request, like
$http.get('http://api.domain.com/index?abc=123&token=456')...
I know a way to send token via header:
$http.defaults.headers.common['X-AUTH-TOKEN'] = token;
But i want use it as parameter, can i?
Regards!
You can use the params option in config of $http
var myHttpConfig = {
params: {
abc: 123,
token: 456
}
}
$http.get( url, myHttpCongig).then(function...
If you want an app wide approach to send the same params use $http interceptors
Note that success and error are now deprecated per the $http docs

$resource invalidation in angularjs

I have this use case where I pass authToken to every request and this token changes everytime the person logins.
app.factory('Comment', function ($resource, localStorageService, $cacheFactory) {
return $resource('http://localhost:port/comments/:id', {"id":"#id", port:':9000'}, {
query: { method:'GET', isArray: true , headers: {'X-AUTH-TOKEN':'authToken='+localStorageService.get("authToken")}},
save: { method:'POST',headers: {'X-AUTH-TOKEN':'authToken='+localStorageService.get("authToken")}},
update: {method:'PUT' ,headers: {'X-AUTH-TOKEN':'authToken='+localStorageService.get("authToken")}},
delete : {method: 'DELETE',headers: {'X-AUTH-TOKEN':'authToken='+localStorageService.get("authToken")}},
get : { method: 'GET', headers: {'X-AUTH-TOKEN':'authToken='+localStorageService.get("authToken")}}
});
The behaviour I am seeing is that if the authToken changes for some reason the $resource keeps adding the previous authToken while sending the request. I am using the $http directly for login and for any commenting related stuff I am using $resource. Am I missing something?
After login I make sure that my localStorage has the newly created token but the request are using the previous authToken till I refresh the page after which it adds the correct header I know that the $resource uses some kind of caching and tried to remove the $http cache like this after loggin in.
$cacheFactory.get('$http').removeAll();
but didnt't help
It's because token is assigned once when factory code executes. Try this instead:
get : { method: 'GET', headers: {
'X-AUTH-TOKEN': function(){
return 'authToken=' + localStorageService.get("authToken");
}
}}

Resources