I'm using jwt-auth for laravel, and angular-js on client side.
This is my typical http request:
.controller('LoginController', function($scope,$rootScope ,$auth, $state, $http, $timeout) {
$http.get('api/loggedIn/getMe').success(function(data) {
//do stuff
}).error(function(error) {
//do stuff
});
})
Every time i send $http request the token side is done automatically, but I want to make one request without using $http, so I need to include my jwt-auth token in headers manualy. (that's because I want to use Dropzone for file upload).
I have something like this:
Dropzone.options.myDropzone = {
sending: function(file, xhr, formData) {
// Pass token
xhr.setRequestHeader('Authorization', 'Bearer: ' + /*This is where I want to put my token*/);
}
};
Edit: this is screenshot from firebug:
Edit: I figured out that satelizer does that nice thing for me, so $auth.getToken() did the trick.
I figured out that satelizer does that nice thing for me, so $auth.getToken() did the trick.
Related
I want to send headers each time for CRUD operation from factory side.
Here is my factory
var appangular.module("LifeStyleFactModule",["ngResource"]);
app.constant("RES_URL", "http://localhost:9090/")
app.factory("CategoryFactory",function($resource,RES_URL){
var categoryinfo;
var categoryresource=$resource(RES_URL+"category/:id",{"id":"#id"},{update:{method:"PUT"}});
return{
getcategory:function(){
categoryinfo=categoryresource.query();
return categoryinfo;
},
addcategoryItem:function(categoryItem){
var category = new categoryresource(categoryItem);
category.$save(function(respdata){
categoryinfo.push(respdata);
},function(respdata){
});
},
deletecategoryItem:function(idx,id){
var category=new categoryresource({"id":id});
category.$delete(function(){
categoryinfo.splice(idx,1);
},function(){
})
},
updatecategoryItem:function(categoryItem,idx){
var category=new categoryresource(categoryItem);
category.$update({"id":categoryItem._id},function(data){
categoryinfo[idx]=data;
},function(){
})
}
}
})
the above functionality is working well. Now i want to send the token in the headers. How can i do that.
I have tried to do it by the following way
var categoryresource=$resource(RES_URL+"category/:id",{"id":"#id"},{update:{method:"PUT"},headers:{"token":"#token}});
but not getting how to send the token for CRUD operation.
Is procedure is correct, if so how can i send tokens.
Else let me know the way.
Instead of above method i tried the following way as
$resource(RES_URL+"category",{},{query:{method:"get",isArray:true,headers:{"token":token}}}).query({},function(res){});
this is working but the procedure for the first procedure.
Please after answering mark it as duplicate or down vote
dont say ( / { such things are missing.
The best solution as to me is to use interceptor. Here is a way to send token in headers, I've used in one of my projects.
angular
.module('app.core')
.config(config);
config.$inject = ['$httpProvider'];
function config($httpProvider) {
$httpProvider.interceptors.push(interceptor);
}
interceptor.$inject = ['$q', '$injector', 'AuthModel'];
function interceptor($q, $injector, AuthModel) {
return {
request: function (config) {
config.headers.Authorization = AuthModel.token;
return config;
},
responseError: function (rejection) {
}
};
}
Added a jsfiddle to demonstrate
https://jsfiddle.net/Sergey_Mell/c47js1zc/
Just click the Send button and check the request headers in developer tools
I'm trying load this json file from remote url. In the beginning I was using $http.get function, but I was getting the next error message:
CORS 'Access-Control-Allow-Origin'
Now I am using JSONP, but nothing happens.
service.js file:
angular.module("elcomaApp").factory('ElcomaService', ['$http', function($http){
return $http({
method: 'JSONP',
url: 'http://vagalumewifi.com.br/timeline.json'
}).success(function(response){
return response.data;
}).error(function(err){
return err;
});
}]);
controller.js file:
angular.module("elcomaApp", []).controller('MainController', ['$scope', 'ElcomaService', function($scope, ElcomaService){
$scope.name = 'Natanael Santos';
console.log($scope.name);
ElcomaService.success(function(data){
$scope.elcomaData = JSON.parse(data);
var i = 0;
for (x in $scope.elcomaData){
console.log(i);
i++;
console.log(x.date);
}
}).error(function(data){
console.log(data);
});
}]);
app.js file:
var app = angular.module("elcomaApp", ['ngMaterial', 'ngRoute']);
I already hava read a lot of articles on stackoverflow, but no one work for me.
I'd suggest using $http.jsonp(url) method:
angular.module("elcomaApp").factory('ElcomaService', ['$http', function($http) {
$http.jsonp('http://vagalumewifi.com.br/timeline.json')
.success(function(data) {
console.log(data); // you can't `return` here...
}).error(function(err){
console.err(err);
});
}]);
Note: be warned that you can't expect that return in an async method has the same behavior as in a sync environment... :-)
Your original error is your clue. The endpoint server won't allow access from another domain.
CORS: Cross Origin Requests
You need to allow access on the endpoint server for the type of HTTP method you want to use (i.e. GET, POST, HEAD, ...) Additionally depending on what you're doing you may need to allow for an OPTIONS request, see Preflighted Requests in the MDN documentation above.
If you don't have access to that server you may need to do a work around by making $http call a script on your server that will fetch the file for you. I've done this before using PHP as a proxy and using PHP's file_get_contents function to grab files from other servers of a different domain.
I'm trying to setup token auth but can't seem to figure out a good way to save the headers the server is sending me into a cookie. I then need to read that value out of the cookie and into the new request headers.
I'm using Angular 1.5
Here's some simple code I've been trying to work with:
os.config(['$httpProvider', function ($httpProvider) {
return {
'request': function(config) {
var access_token = $cookies.get('access-token');
var token_type = $cookies.get('token-type');
var client = $cookies.get('client');
var uid = $cookies.get('uid');
$httpProvider.defaults.headers.post['access-token'] = access_token;
$httpProvider.defaults.headers.post['token-type'] = token_type;
$httpProvider.defaults.headers.post['client'] = client;
$httpProvider.defaults.headers.post['uid'] = uid;
},
'response': function(response) {
$cookies.put('access-token', 'oatmeal');
$cookies.put('token-type', 'oatmeal');
$cookies.put('client', 'oatmeal');
$cookies.put('uid', 'oatmeal');
}
};
}]);
EDIT: People have been commenting trying to show me how to set headers. I can do that easily, as you can see in the example. What I need to do is save the response headers after I've made a request. These need to be saved into a cookie which is what my question pertains to.
I'm interested in a method that doesn't require me to run some function in the .then part of every single API request I do, that's not DRY and seems like madness...
I am building an authentication solution with Angular. I am using Interceptors to validate Request and if there is not valid token prevent from further processing and redirect. Here is my simplified Interceptor:
prism.service('APIInterceptor', function($rootScope) {
var service = this;
service.request = function(config) {
.....
return config;
};
})
Just for the sake of POC that I am working on what would the correct way of stopping this request from any further processing be?
Thanks
From the Angular Docs on Interceptors for the request method:
request: interceptors get called with a http config object. The function is free to modify the config object or create a new one. The function needs to return the config object directly, or a promise containing the config or a new config object.
The rest of the documentation can be found here. From this you can see that the method can also return a promise (which is actually pretty awesome) so you could always reject it.
Try something like this:
prism.service('APIInterceptor', function($q, $rootScope) {
this.request = function(config) {
if( /*config is not valid*/ ) {
return $q.reject({message: 'ERROR, ERROR... INTRUDER ALERT!', status: 401, config: config});
} else {
return config;
}
};
});
And see how it might be handled (I have no idea what your application will do). Let me know if it works out for you!
EDIT: My answer has been accepted, but is incomplete and it will haunt me forever if I don't complete it. So, after writing some test code of my own I've realized that you can do 1 of 2 things in this situation. The first is to handle the unauthorized request in the interceptor:
...
this.request = function(config) {
if(/* config is not authorized */) {
// Do something here like redirect/issue another request... whatever
return $q.reject({/*whatever the hell you want*/});
} else ...
};
...
This obviously works best if you want to handle all unauthorized requests the same. If you don't, however, the second option is to defer to the service that issued the request. For example, if you're using $http you can do this:
$http.get('/words/words/words/').then(function(){
// This is where you handle a successful request.
}, function(error) {
// Handle your error here. Please take note that this error message is
// whatever you sent back in the `reject` previously
});
Hopefully that clears a few things up.
In my angular app, I have a $http request interceptor called 'authInterceptor' that I create like this:
.factory('authInterceptor', function ($q, $window, EXT_API_BASE, $injector) {
return {
request: function (config) {
if (config.url.indexOf(EXT_API_BASE) !== -1){
var Auth = $injector.get('Auth');
if(Auth.user && Auth.user.token){
config.headers.Authorization = 'Web ' + Auth.user.token;
}
}
return config;
}
}});
It gets registered in a .config():
$httpProvider.interceptors.push('authInterceptor');
As you see, my Authorization headers are bound to a Auth.user.token value. This value is available when my user is signed in.
Then the headers are sent for any calls to my api.
The problem I am facing is... when the user signs out in my angular app, the Authorization headers are still being sent even though I deleted Auth.user.token already.
On a hard refresh of the page, the Authorization headers then get removed completely.
How can I make sure 'authInterceptor' registers the change in token value when my user signs out?
Answering my own question. Made a newbie mistake of changing Auth.user object like this on sigh out:
Auth.user = {}
That created a new object and the requestInterceptor was still referencing the old object.
The correct way to do it is:
delete Auth.user.token