Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular js add request parameter on every http request $http

I'd like to use angular $http to interact with api, but I need to store my auth token to $http so that in every request wether post get put delete, I want the token to be present, also I have seen people place tokens in the header , I know how to place it in the header, but I'm not sure if its a good practice to put tokens in the header , here is my config :

config(['$stateProvider', '$urlRouterProvider','$http', function($stateProvider, $urlRouterProvider, $http) {
  $urlRouterProvider.otherwise("/view1");

}]);
like image 800
Mikail Avatar asked Sep 29 '26 21:09

Mikail


2 Answers

To communicate with an API that requires token authentification, you need to set up an interceptor.

In your config file:

function config(..., $httpProvider) {
    $httpProvider.interceptors.push('authInterceptor');
    ...
}
angular
    .module('app')
    .config(config);

authInterceptor is a factory that will take care of adding headers to all your $http requests:

function authInterceptor($rootScope, $q, $window) {
    return {
        request: function (config) {
            config.headers = config.headers || {};
            if ($window.sessionStorage.token) {
                config.headers.Authorization = 'Bearer ' + $window.sessionStorage.token;
            }
            return config;
        },
        responseError: function (rejection) {
            if (rejection.status === 401) {
                console.log("not authorised");
            }
            return $q.reject(rejection);
        }
    };
};

angular
    .module('app')
    .factory('authInterceptor', authInterceptor);

The token can come from sessionStorage, cookies or anything.

like image 86
gyc Avatar answered Oct 02 '26 01:10

gyc


config $httpProvider at start up!

'use strict';

angular.module('app')
    .config(configHttp);

configHttp.$inject = ['$httpProvider'];
function configHttp($httpProvider) {
    if (!$httpProvider.defaults.headers.get) {
        $httpProvider.defaults.headers.get = {};
    }
    //disable IE ajax request caching
    $httpProvider.defaults.headers.get['If-Modified-Since'] = 'Mon, 26 Jul 1997 05:00:00 GMT';
    // extra
    $httpProvider.defaults.headers.get['Cache-Control'] = 'no-cache';
    $httpProvider.defaults.headers.get.Pragma = 'no-cache';
    // User Credential
    $httpProvider.defaults.headers.post['user-credential'] = 'xxxxxx';
}
like image 32
zhimin Avatar answered Oct 02 '26 01:10

zhimin