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");
}]);
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.
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';
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With