Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keycloak Unknown Provider error

I'm using Keycloak.js for interaction with Keycloak and getting below error

Uncaught Error: [$injector:unpr] Unknown provider: AuthProvider <- Auth <- authInterceptor <- $http <- $templateRequest <- $compile

With below code:

module.factory('authInterceptor', ['$q', 'Auth', function($q, Auth) {
  return {
    request: function (config) {
      var deferred = $q.defer();
      if (Auth.authz.token) {
        Auth.authz.updateToken(5).success(function() {
          config.headers = config.headers || {};
          config.headers.Authorization = 'Bearer ' + Auth.authz.token;

          deferred.resolve(config);
        }).error(function() {
          deferred.reject('Failed to refresh token');
        });
      }
      return deferred.promise;
    }
  };
}]);

module.config(['$httpProvider', function($httpProvider) {
  $httpProvider.responseInterceptors.push('errorInterceptor');
  $httpProvider.interceptors.push('authInterceptor');
}]);

Is there a reason why this is happening?

I am also including keycloak.js in my index.html which is inserted with Bower

I also have below Auth factory instantiated inside dom ready:

angular.element(document).ready(function($http) {
  var keycloakAuth = new Keycloak('keycloak.json');
  auth.loggedIn = false;

  keycloakAuth.init().success(function () {
    auth.loggedIn = true;
    auth.authz = keycloakAuth;
    auth.logoutUrl = keycloakAuth.authServerUrl + "/realms/demo/tokens/logout?redirect_uri=http://localhost:3000";
    module.factory('Auth', function () {
      return auth;
    });
  }).error(function () {
    window.location.reload();
  });
});
like image 679
Passionate Engineer Avatar asked Jan 29 '15 10:01

Passionate Engineer


2 Answers

the problem is that you are instantiating "Auth" on dom ready, but the dependecy injector is trying to inject before the dom ready (simplifying).

The question is why on dom ready?

here are two examples:

http://jsbin.com/lulin/1/edit (with on dom ready definition, not working, same error)

http://jsbin.com/wajeho/2/edit (without on dom ready definition,working)


EDIT:

You have to do something like this: http://jsbin.com/xusiva/1/edit?html,js,console

I'm difining the factory outside the domready, and inside the controller after domready i'm using it.

like image 59
hayatoShingu Avatar answered Nov 14 '22 22:11

hayatoShingu


I have the same problem, so far for what I can tell is that the example of Keycloak is running angular 1.2, and you are probably using the latest 1.3.
If you try Keycloak angular example with angular 1.2 it works, but when you try it with 1.3 you get that error.

I have being reading about this and it has to do with the interceptors, the way they are declared in angular 1.3 is different. Also, responseInterceptors are completly deprecated in angular 1.3.

like image 40
Juan Diego Avatar answered Nov 14 '22 21:11

Juan Diego