Secure header or cookie with Angular 1.6 interceptor Secure header or cookie with Angular 1.6 interceptor angularjs angularjs

Secure header or cookie with Angular 1.6 interceptor


I can't add a comment because of my rep but what are you doing on the back-end to authorize users? If the cookie is signed and contains user permissions it shouldn't matter that the header is visible in the client as it will also be verified on the back-end API call.


in this sample i used HttpRestService to get RESTful API, read this article

at first we create a service to get our configs in this sample is getConfigs

we use getConfigs in the app.run when application is started, after get the configs we set them all in the header as sample.

after that we can get userProfile with new header and also secure by call it from our controller as you see.

in this sample you need to define apiUrl, it's your api host url, remember after logout you can remove the header, also you can define your configs dynamically to make more secure for your application.

HttpRestService.js github link

app.js

var app = angular.module("app", ["HttpRestApp"]);

app.service

app.service("service", ["$http", "$q", "RestService", function (http, q, restService) {    this.getConfigs = function () {        var deferred = q.defer();        http({            method: "GET",            async: true,            headers: {                "Content-Type": "application/json"            },            url: "you url to get configs"        }).then(function (response) {            deferred.resolve(response.data);        }, function (error) {            deferred.resolve(error);        });        return deferred.promise;    }    var api = {        user: "User" //this mean UserController    }    //get user with new header    //this hint to your api with this model "public Get(int id){ return data; }"    //http://localhost:3000/api/users/123456    this.getUserProfile= function(params, then) {        restService.get(params, api.user, true).then(then);    }}]);

app.run

app.run(["RestService", "service", function (restService, service) {   var header = {      "Content-Type": "application/json"   }   //get your configs and set all in the header   service.getConfigs().then(function (configs) {      header["systemId"] = configs.systemId;   });   var apiUrl = "http://localhost:3000/";   restService.setBaseUrl(apiUrl, header);}]);

app.controller

app.controller("ctrl", ["$scope", "service", function ($scope, service) {    $scope.getUserProfile = function () {        //this is just sample        service.getUserProfile({ id: 123456 }, function (data) {            $scope.user = data;        });    }       $scope.getUserProfile();}]);