Set HTTP header for one request
Asked Answered
K

2

161

I have one particular request in my app that requires Basic authentication, so I need to set the Authorization header for that request. I read about setting HTTP request headers, but from what I can tell, it will set that header for all requests of that method. I have something like this in my code:

$http.defaults.headers.post.Authorization = "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==";

But I don't want every one of my post requests sending this header. Is there any way to send the header just for the one request I want? Or do I have to remove it after my request?

Keramics answered 9/8, 2012 at 4:22 Comment(0)
M
324

There's a headers parameter in the config object you pass to $http for per-call headers:

$http({method: 'GET', url: 'www.google.com/someapi', headers: {
    'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
});

Or with the shortcut method:

$http.get('www.google.com/someapi', {
    headers: {'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
});

The list of the valid parameters is available in the $http service documentation.

Mariannemariano answered 9/8, 2012 at 4:39 Comment(15)
I guess I should have looked at the doc a little closer... I was just trying to use the shortcut methods. This works great. Thanks.Keramics
@Keramics This works with shortcut methods too. The code would be $http.get('www.google.com/someapi', {headers: {'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}});Mariannemariano
Is there a way to extend $http (while maintaining "injectability" and not having to apply it to the default header collection) to automatically add this header for you? Seems kind of redundant to always have to add the header for every secure call you make.Caparison
@Caparison You can create your own service myHttp which composes $http and adds your headers. Then you can inject myHttp where you want.Mariannemariano
@woody, I am a complete newb with angular. I tried to do exactly that (I think) but injection failed. I based my solution on this: groups.google.com/forum/m/#!msg/angular/72ukcZYeWGE/…Caparison
@Caparison Refer to the doucmentation for Angular services. If you need more help, you'll get a much better answer if you post your own question.Mariannemariano
@woody, will do. Like I said I am a newb :)Caparison
Doesn't work for me. None of the headers I add in this way get added to the actual request.Ranson
so anybody can answer how to send username and password, and explain what base64 is doing in here, and how angular.js can handle this for me? Thanks!Septuor
@Septuor the username and password are being encoded in base64 before being sent to the server. See: en.wikipedia.org/wiki/Basic_access_authenticationHandicapped
Whenever I try to set the headers, my request goes out as an OPTION Request, consequently my endpoint returns a 404 NOT FOUND which makes sense: It only knows a GET /someResource not OPTIONS /someResourceSheldonshelduck
@MatheusFelipe did you get it to work, I have the same problem my request also goes out with OPTION requestConias
@Conias I got it to work! Sometimes things are so obvious that get overlooked 1- As I had stated before my server didn't know how to reply a OPTIONS request. Now I simply created a route for all URI, such as OPTIONS /* will call my MyController.Cors method. 2- I needed to set the response header as Access-Control-Allow-Origin", "*" -- Note that I placed "*" because it's just an experiment, in real world you'd want to really filter by the correct expected origin. 2.1- Since I use AUTHORIZATION header on my app I also had to set "Access-Control-Allow-Headers", "Authorization"Sheldonshelduck
This looks like it makes sense, but how can I send a dynamic Authorization code? I need my user to login and then have their credentials stored for every post request. Thanks.Flew
@MatheusFelipe just to add to what you said about the OPTIONS request, I had to do something similar within my API backend because browsers issue an OPTIONS request without the auth header as a preflight to any cross-origin AJAX request. I had it respond 204 (OK, no content) to any URL in my API directory and my auth script has a conditional that skips basic auth if it's an HTTP OPTIONS request. I had to issue Access-Control-Allow-Headers: Authorization in my OPTIONS response as well.Rowboat
B
20

Try this, perhaps it works ;)

.factory('authInterceptor', function($location, $q, $window) {


return {
    request: function(config) {
      config.headers = config.headers || {};

      config.headers.Authorization = 'xxxx-xxxx';

      return config;
    }
  };
})

.config(function($httpProvider) {
  $httpProvider.interceptors.push('authInterceptor');
})

And make sure your back end works too, try this. I'm using RESTful CodeIgniter.

class App extends REST_Controller {
    var $authorization = null;

    public function __construct()
    {
        parent::__construct();
        header('Access-Control-Allow-Origin: *');
        header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Authorization");
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
        if ( "OPTIONS" === $_SERVER['REQUEST_METHOD'] ) {
            die();
        }

        if(!$this->input->get_request_header('Authorization')){
            $this->response(null, 400);    
        }

        $this->authorization = $this->input->get_request_header('Authorization');
    }

}
Bengal answered 27/11, 2014 at 4:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.