We have built an RestFul API implementing OAuth 2.0
Now I want to connect an AngularJS frontend using Restangular and oauth-ng
But how can I get both to interact regarding the oauth token?
Oauth-ng should handle login/logout and token refreshing. Restangular should fetch the access_token from oauth-ng to send the token with all requests.
My current code is implemented like this.
angular
.module('myapp', ['oauth','restangular'/* ... */ ])
.config(function ($routeProvider,$locationProvider,RestangularProvider,AccessToken) {
$routeProvider
.when('/access_token=:accessToken', {
template: '',
controller: function ($location, AccessToken) {
var hash = $location.path().substr(1);
AccessToken.setTokenFromString(hash);
console.log(AccessToken); //THIS WORKS
$location.path('/');
$location.replace();
}
})
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode({
enabled: true,
requireBase: true
}).hashPrefix('!');
RestangularProvider.setBaseUrl('https://myapi.local/');
// next line throws error
RestangularProvider.setDefaultHeaders({Authorization: 'Bearer ' + AccessToken.get()});
});
But this code throws an error "Unknown provider: AccessToken".
Seems like "AccessToken" is not yet available at the config stage. But I do not want to implement this general function in every controller again and again.
What would be a good way to connect both modules?
Thanks for your help!
The AccessToken var is not injected in the scope you're using it. Did you try moving setting the Token for Restangular to the point where you fulfill your promise. Example:
angular
.module('myapp', ['oauth','restangular'/* ... */ ])
.config(function ($routeProvider,$locationProvider,RestangularProvider) {
$routeProvider
.when('/access_token=:accessToken', {
template: '',
controller: function ($location, AccessToken) {
var hash = $location.path().substr(1);
AccessToken.setTokenFromString(hash);
RestangularProvider.setDefaultHeaders({Authorization: 'Bearer ' + AccessToken.get()});
console.log(AccessToken); //THIS WORKS
$location.path('/');
$location.replace();
}
})
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode({
enabled: true,
requireBase: true
}).hashPrefix('!');
RestangularProvider.setBaseUrl('https://myapi.local/');
});