Reputation: 68
This seems like a simple case: I'm trying to add a request interceptor to add OAuth bearer tokens to $http requests using Angular 1.1.5. Here's my interceptor:
app.factory('bearerTokenInterceptor', function($injector, $q) {
/*
* This interceptor is available for providers that use the header based
* bearer token for authentication
*/
return {
request: function(config) {
/*
* We need to use $injector to get access to the Token provider within
* the body of the ctor - lest we want circular references created
* by providers that need to use the interceptor (and also need the
* Token provider
*/
var Token = $injector.get('Token');
config.headers.get = {'Authorization': 'Bearer ' + Token.get() };
return config || $q.when(config);
}
};
});
and then
app.config(function(TokenProvider, YammerTokenVerifier, $httpProvider) {
TokenProvider.extendConfig({
authorizationEndpoint: 'https://www.yammer.com/dialog/oauth',
verifyFunc: YammerTokenVerifier
});
/*
* Yammer uses a bearer token - in comes the BearerTokenInterceptor!
*/
$httpProvider.interceptors.push('bearerTokenInterceptor');
});
But when I actually then use $http
$http.get('https://www.yammer.com/api/v1/users/current.json')
.success(function(data) {
deferred.resolve(data);
})
.error(function(data, status, headers, config) {
console.log(data);
console.log(status);
console.log(headers);
console.log(config);
deferred.reject(data);
});
The request interceptor is not getting called. I don't see anything I'm doing that is beyond what the Angular docs suggest. What am I missing?
Upvotes: 2
Views: 2570
Reputation: 48982
I tried your code and it's ok. You just need to ensure that you're actually using angular js. 1.1.5. Try this: https://ajax.googleapis.com/ajax/libs/angularjs/1.1.5/angular.min.js
Because with previous versions, $httpProvider.interceptors
is undefined and trying to call $httpProvider.interceptors.push('bearerTokenInterceptor');
throws exception.
Update:
If you register your factory in another module, you need to add a dependency to that module using a code like this:
var app = angular.module('yourapp',['factoryModule']);
app.config(function(TokenProvider, YammerTokenVerifier, $httpProvider) {
TokenProvider.extendConfig({
authorizationEndpoint: 'https://www.yammer.com/dialog/oauth',
verifyFunc: YammerTokenVerifier
});
$httpProvider.interceptors.push('bearerTokenInterceptor');
});
Upvotes: 4