0

my message is based on this message http://stackoverflow.com/questions/26748106/how-to-manage-authentication-with-token-in-angular-js I have a backend with PHP5(Symfony2) and a front end with (angularJS) I have succeeded to create tokens with the backend,but I got a problem with angularjs,I have to get the token from the URL and to put it in every request to get client lists per example,this is what I did:

the controller:signin.js

'use strict';
  // signin controller
app.controller('SigninFormController', ['$scope','$http', '$state','$localStorage','authorizationInterceptor', function($scope, $http, $state,$localStorage,authorizationInterceptor) {
    $scope.user = {};
    $scope.authError = null;
    $scope.login = function() {
    $scope.authError = null;
      // Try to login
    $http({method: 'POST', url: 'myURL/oauth/v2/token?client_id=clientID&client_secret=clientSecret&grant_type=client_credentials'})
   .success(function(response){
     if (response.data.user) {  
     $scope.errors.splice(0, $scope.errors.length); 
     $scope.msgs.splice(0, $scope.msgs.length);
     $scope.posts = data; // response data 
     var token = this.$window.sessionStorage($scope.posts.access_token);
     console.log(""+token);
     console.log("success");
     $state.go('app.home');}
   })
   .error(function(data, status, headers, config) {
    $scope.authError = 'Email or Password not right';
    console.log("data error ...");
  });

    };

and my services :access-services.js

.factory('Security', ['$http', function ($http) {
        var token;
        function login(email, password) {
            return $http.post('/auth/login', {email: email, password: password})
                .then(function (response) {

                    if (response.data.token) {
                        token=response.data.token;
                    }
                });
        }

        function getToken(){
            return token;
        }

        return {
            login:login,
            token:getToken
        }; }])
.factory('authorizationInterceptor', ['Security', function (Security) {
        return {
            request: function (config) {
                var token=Security.getToken();
                config.headers = config.headers || {};
                if (token) {
                    config.headers.Authorization = 'Bearer ' + token;
                }
                return config;} }; }]);

but this is what I get in console: enter image description here

thanks for help

0

2 Answers 2

1

You have to angular to use the token interceptor. This can be done at the app config phase

yourApp.config(function($httpProvider) {
    $httpProvider.interceptors.push("authorizationInterceptor");
});

I suggest you read the following series of articles. Though they are written targeting ASP.net MVC, concepts presented are universal

http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/

Hope this helps

Sign up to request clarification or add additional context in comments.

4 Comments

thanks Chintana Meegamarachc,I have add those lines to my config file:thanks Chintana Meegamarachc,I have add those lines to my config file:.config(['$httpProvider',function ($httpProvider) { $httpProvider.interceptors.push('TokenInterceptor'); }]) but I get this error : Uncaught Error: [$injector:unpr] Unknown provider: TokenInterceptorProvider <- TokenInterceptor <- $http <- $translateStaticFilesLoader
can you change it to $httpProvider.interceptors.push("authorizationInterceptor");
always the same problem :( -> Uncaught Error: [$injector:cdep] Circular dependency found: $http <- Security <- authorizationInterceptor <- $http <- $translateStaticFilesLoader
Its probably because you are using 'Security' service as dependency to the interceptor and the interceptor is being called from Security service when it does the http call. The best thing to do is to create another service to hold the token and use it with both the 'Security' service and the inteceptor
1

use a token interceptor like this:

app.factory('TokenInterceptor', function($q, $window) {
  return {
    request: function(config) {
      config.headers = config.headers || {};
      if ($window.sessionStorage.token) {
        config.headers['X-Access-Token'] = $window.sessionStorage.token;
        config.headers['X-Key'] = $window.sessionStorage.user;
        config.headers['Content-Type'] = "application/json";
      }
      return config || $q.when(config);
    },

    response: function(response) {
      return response || $q.when(response);
    }
  };
});

and then use it in your app.config like this

$httpProvider.interceptors.push('TokenInterceptor');

2 Comments

thanks @Viki and the controller,should I call the service from the controller??
You dont need to call anything, once you add $httpProvider.interceptors.push('TokenInterceptor'); every request will have the token injected in header if the sessionstorage has token. Look how @Chintana Meegamarachchi pushed interceptors in $httpProvider. Sorry, new to stackoverflow and not used to this editor.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.