Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
AngularJS service to send auth token with $resource requests
.factory('TokenHandler', function() {
var tokenHandler = {};
var token = "none";
tokenHandler.set = function( newToken ) {
token = newToken;
};
tokenHandler.get = function() {
return token;
};
// wrap given actions of a resource to send auth token with every
// request
tokenHandler.wrapActions = function( resource, actions ) {
// copy original resource
var wrappedResource = resource;
for (var i=0; i < actions.length; i++) {
tokenWrapper( wrappedResource, actions[i] );
};
// return modified copy of resource
return wrappedResource;
};
// wraps resource action to send request with auth token
var tokenWrapper = function( resource, action ) {
// copy original action
resource['_' + action] = resource[action];
// create new action wrapping the original and sending token
resource[action] = function( data, success, error){
return resource['_' + action](
angular.extend({}, data || {}, {access_token: tokenHandler.get()}),
success,
error
);
};
};
return tokenHandler;
});
@denen99

This comment has been minimized.

Copy link

denen99 commented Aug 23, 2013

Is there a way to persist this across browser refreshes ?

@pavelnikolov

This comment has been minimized.

Copy link

pavelnikolov commented Sep 4, 2013

@denen99 you can use cookies with ng-cookie - here you can find how to do it http://stackoverflow.com/questions/10961963/how-to-access-cookies-in-angularjs. The documentation is good enough yet http://docs.angularjs.org/api/ngCookies.$cookies

@JeremyPinhel

This comment has been minimized.

Copy link

JeremyPinhel commented Feb 21, 2014

How can i custom headers for each resource action ?

@ahmadina

This comment has been minimized.

Copy link

ahmadina commented Jul 15, 2014

is this secure?

@venkatramachandran

This comment has been minimized.

Copy link

venkatramachandran commented Jul 29, 2014

How would I modify this to add custom headers?

@zaypen

This comment has been minimized.

Copy link

zaypen commented Sep 14, 2015

I had lost my 'params' while using this way.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.