2017-06-16 98 views
1

授權標頭未使用HTTP OPTIONS請求發送。我希望只有在請求是OPTIONS時才禁用此認證,並將其保留爲其他請求。這裏是我現在有的配置代碼片段。似乎無法看出它爲什麼不起作用。我總是在OPTIONS請求中獲得401 Unauthorized Error。nginx:僅在HTTP請求爲選項時才需要基本身份驗證選項

location ~ /foo/bar 
    { 

     if ($request_method = OPTIONS) { 
     set $auth_basic "off"; 
     } 
     if ($request_method != OPTIONS) 
     { 
     set $auth_basic "Resctricted"; 
     set $auth_basic_user_file /var/www/.htpasswd; 
     } 
     auth_basic $auth_basic; 
     auth_basic_user_file $auth_basic_user_file; 
    } 

回答

0

處理這個最簡單的方法是讓nginx的處理OPTIONS要求:

server { 
    listen 80; 
    server_name example.com; 
    root /var/www; 

    auth_basic "Resctricted"; 
    auth_basic_user_file /var/www/.htpasswd; 

    location/{ 
     if ($request_method = OPTIONS) { 
      add_header Access-Control-Allow-Origin "http://example.com"; 
      add_header Access-Control-Allow-Methods "GET, OPTIONS"; 
      add_header Access-Control-Allow-Headers "Authorization"; 
      add_header Access-Control-Allow-Credentials "true"; 
      add_header Content-Length 0; 
      add_header Content-Type text/plain; 
      return 200; 
     } 
    } 
} 

這將使OPTIONS獲得,而不需要認證的響應:

[email protected] www $ curl -i -X OPTIONS http://example.com 
HTTP/1.1 200 OK 
Server: nginx 
Date: Sat, 17 Jun 2017 00:09:52 GMT 
Content-Type: application/octet-stream 
Content-Length: 0 
Connection: keep-alive 
Access-Control-Allow-Origin: http://example.com 
Access-Control-Allow-Methods: GET, OPTIONS 
Access-Control-Allow-Headers: Authorization 
Access-Control-Allow-Credentials: true 
Content-Length: 0 
Content-Type: text/plain 

[email protected] www $ curl -i http://example.com 
HTTP/1.1 401 Unauthorized 
Server: nginx 
Date: Sat, 17 Jun 2017 00:09:59 GMT 
Content-Type: text/html 
Content-Length: 188 
Connection: keep-alive 
WWW-Authenticate: Basic realm="Resctricted" 

<html> 
<head><title>401 Authorization Required</title></head> 
<body bgcolor="white"> 
<center><h1>401 Authorization Required</h1></center> 
<hr><center>nginx</center> 
</body> 
</html> 
+0

感謝您的回答。我在你的幫助下提出了這個問題。這不對嗎?驗證碼必須在那裏,因爲這是唯一需要它的位置。我仍然得到401未經授權。 '位置〜/富/酒吧/ { 如果($ REQUEST_METHOD = OPTIONS){ ... 返回200; } auth_basic「Restricted」; auth_basic_user_file /var/www/.htpasswd; }' –

0

它看起來像是一箇舊帖子,但找到了這個解決方案:

在「位置」中放入以下配置,並從服務器中刪除任何auth_basic。這將工作

location/{ 
    # Your node proxy configuration for example # 

    # Make options requests work # 
    limit_except OPTIONS { 
     auth_basic "Restricted access zone"; 
     auth_basic_user_file /etc/nginx/pass/protected; 
    } 
    }