Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass authtoken via header using angular js

I am trying to pass my api authtoken via the header. I am new to angular js so i am not able to do that. My code:

$scope.init=function(authtoken,cityname){   
        $scope.authtoken=authtoken;                     
        $scope.cityname=cityname;               
        $http({method: 'GET', url: '/api/v1/asas?city='+$scope.cityname+'&auth='+$scope.authtoken}).success(function(data) {                

Right now I am passing the authtoken in the api url. But I want to pass the token via the header.

like image 772
Himanshu Bhuyan Avatar asked Sep 19 '14 12:09

Himanshu Bhuyan


People also ask

How do I pass a header token?

To send a request with the Bearer Token authorization header, you need to make an HTTP request and provide your Bearer Token with the "Authorization: Bearer {token}" header. A Bearer Token is a cryptic string typically generated by the server in response to a login request.

How do I add auth token in header?

The token is a text string, included in the request header. In the request Authorization tab, select Bearer Token from the Type dropdown list. In the Token field, enter your API key value. For added security, store it in a variable and reference the variable by name.

What is Bearer Token in angular?

This type of token is known as a Bearer Token, meaning that it identifies the user that owns it, and defines a user session. A bearer token is a signed temporary replacement for the username/password combination!


2 Answers

usually you pass auth token in headers. Here is how i did it for one of my apps

angular.module('app', []).run(function($http) {
        $http.defaults.headers.common.Authorization = token;
    });

this will add auth token to headers by default so that you wont have to include is every time you make a request. If you want to include it in every call then it will be something like this

$http({
    method: 'GET', 
    url: '/api/v1/asas?city='+$scope.cityname,
    headers:{
        'Authorization': $scope.authtoken
    }
}).success(function(data) {
    //success response.
}).error(function(error){
    //failed response.
});
like image 113
khizar naeem Avatar answered Oct 25 '22 10:10

khizar naeem


You can configure on application run

youapp.run(function($http) {
    $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w'
});

or pass it throw each request

$http({
    url:'url',
    headers:{
        Authorization : 'Basic YmVlcDpib29w'
    }
})

Angular $Http reference

like image 40
BlaShadow Avatar answered Oct 25 '22 10:10

BlaShadow