0

I would like to set-up a basic HTTP-Authentication using JQuery on the client-side and Node.js on the server side. I have made the following Ajax request on the server side to set the headers:

$.ajax({
        type: "GET",
        url: URL_SLACK_SERVER,
        dataType: "json",
        beforeSend: function(xhr){
            xhr.setRequestHeader("Authorization", "Basic " +btoa("username:xxx") );
        },
        success:function(rsp){
            filterMessages(rsp);
        }
    });

Which I want to use on my server side using the basic-auth module:

var express = require('express');
var bodyParser = require('body-parser');
var auth = require('basic-auth');

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Authorization, Accept, Key");
  var cre = +auth(req);
  console.log('Auth: ' +cre.username);
  next();
});

But, doing this way, I encounter some issues:

  1. I do not see that the header are set in the preflight OPTIONS HTTP request:

OPTIONS /server HTTP/1.1
Host: server.com
Connection: keep-alive
Access-Control-Request-Method: GET
Origin: null
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36
Access-Control-Request-Headers: accept, authorization
Accept: /
Accept-Encoding: gzip, deflate, sdch
Accept-Language: en-US,en;q=0.8,fr;q=0.6

  1. I got the following error, which I do not understand well:

Request header field Authorization is not allowed by Access-Control-Allow-Headers in preflight response.

Also, please note that the call from the client to the server is a cross-domain call, that's why there is these set headers written on the Node.js file.

How can I efficiently perform this basic HTTP-Authentication?

Mornor
  • 3,471
  • 8
  • 31
  • 69
  • Looks like your server and client are running on different domain and the server doesn't have proper CORS headers set. – Harsha Bhat Jan 19 '16 at 09:26
  • They indeed run on different domain (see the end of my question). Which headers can I add on the server side? – Mornor Jan 19 '16 at 09:27

2 Answers2

1

Since your client and server are running on different domains, you need to configure the CORS header in your server to make it work.

You need to set the header "Access-Control-Allow-Origin:http://foo.example" or "Access-Control-Allow-Origin:*" in your server.

Harsha Bhat
  • 718
  • 10
  • 25
1

Yes its a cors problem. When you enable cors in npm (Look for cors module and append it via npm) you can set a specific domain that is allowed. When you set this the basic authentication header will be send with the request. Look at this request: https://stackoverflow.com/a/18511690/3232739

Community
  • 1
  • 1
user3232739
  • 143
  • 1
  • 8