从域A的网页开始,我向域B发出ajax请求,以获取在域B上配置了基本身份验证的JSON。我可以访问两个域上的代码。
我在域B上配置了所有必需的CORS标头(在读取了一些stackoverflow之后,即使将Access-Control-Allow-Origin标头值指定为特定值,也并非“ *”)
我期望弹出浏览器的基本身份验证,但是POST请求只是失败,并显示401。
我可以看到服务器已使用PRE-FLIGHT OPTION请求的预期响应标头进行了响应,该请求标头位于发生的OPTION和实际POST方法调用
***OPTION REQUEST***
Host: DOMAIN_B:8085
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Access-Control-Request-Method: POST
Access-Control-Request-Headers: x-requested-with
Referer: http://DOMAIN_A:2280/app/
Origin: http://DOMAIN_A:2280
Connection: keep-alive
***OPTION RESPONSE***
HTTP/1.1 200 OK
X-Powered-By: Express
Access-Control-Allow-Origin: http://DOMAIN_A:2280
Vary: Origin
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: GET,HEAD,PUT,PATCH,POST,DELETE
Access-Control-Allow-Headers: Content-Type,Authorization,x-requested-with
Access-Control-Max-Age: 1
Allow: GET,POST
Content-Type: text/html; charset=utf-8
Content-Length: 8
Date: Fri, 04 Jan 2019 12:48:48 GMT
Connection: keep-alive
*** ACTUAL POST REQUEST***
Host: DOMAIN_B:8085
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:64.0) Gecko/20100101 Firefox/64.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://DOMAIN_A:2280/app/
X-Requested-With: XMLHttpRequest
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Content-Length: 105
Origin: http://DOMAIN_A:2280
Connection: keep-alive
*** ACTUAL POST REQUEST***
HTTP/1.1 401 Unauthorized
X-Powered-By: Express
Vary: X-HTTP-Method-Override, Origin
Access-Control-Allow-Origin: http://DOMAIN_A:2280
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: POST,GET,PUT,DELETE
Access-Control-Allow-Headers: Content-Type,Authorization,x-requested-with
Access-Control-Max-Age: 1
WWW-Authenticate: Basic realm=artist
Content-Type: text/plain; charset=utf-8
Content-Length: 12
Date: Fri, 04 Jan 2019 12:48:48 GMT
Connection: keep-alive
因此,它期望浏览器查看POST调用的响应(401 HTTP代码和WWW-Authenticate标头)时,将得到提示以显示本机身份验证弹出窗口,但事实并非如此。我不确定我在做什么错。显示自定义表单以捕获凭证并使用"Authorization"
函数将其传递到btoa
标头中
感谢您的帮助,我在这里把头发扯开了!!!
答案 0 :(得分:0)
使用basic-auth npm插件
const auth = require('basic-auth');
app.use(function (request, response, next) {
var user = auth(request);
console.log("user => ",user);
if (!user || !user.name || !user.pass) {
response.set('WWW-Authenticate', 'Basic realm="example"');
return response.status(401).send();
}
return next();
});