简体   繁体   中英

nginx auth_basic “Restricted” prompting login on every request

I've set up a simple nginx server, configured the location block to point to the respective directories I want served, and setup basic authentication using the auth_basic module.

However, my server requests username : password credentials on every single page request under the location block , even after providing them multiple times to different pages under the location block, including the root location directory.

How can I configure it to store the authentication? Is this an nginx issue or a browser / request headers issue?

Here is the nginx configuration:

server {
    listen 80;
    server_name 0.0.0.0;

    location /path/to/dir {
        alias /var/www/dir/;
        index   index.html index.htm;
        auth_basic "Restricted";
        auth_basic_user_file /etc/nginx/.htpasswd;
        try_files $uri $uri/ =404;
    }
}

Running nginx 1.4.6 on Ubuntu.

我的问题是,在页面加载时由JavaScript调用的API调用之一返回401.这似乎重置了页面的浏览器身份验证状态。

HTTP authentication information is stored on your browser cache, and should only be requested again if the authentication fails or it's from a different realm (in auth_basic "Restricted"; it's Restricted ).

Your configuration is fine, considering your password is correct and Nginx user has read access to the password file (case in which it'll always fail — but send an error message at the log file indicating this error). This is the most probable reason, mainly if you have only one location with authentication.

Another possible reason is having multiple auth_basic directives and they use different realms or passwords. This is the same for application-generated WWW-Authenticate headers (say, if your backend application requests for HTTP authentication in addition to Nginx). When there's a different realm or a password fails, your browser will request it again. No browser that I know of stores authentication per URL, it's always a combination of realm+hostname.

If you do need different realms or passwords on different locations, make sure they don't overlap for a single page (for example, if you use a different password for your assets: images, styles or javascript). Or use different hosts — the password would be requested once for each host/realm combination, though.

Update

It's unusual to use 0.0.0.0 as a server_namelisten 80; already makes your server to listen to all interfaces/IP addresses.

Use server_name _; in case you mean to use any request host.

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