简体   繁体   中英

Basic HTTP authorization header

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM