2017-06-16 6 views
1

HTTP OPTIONS要求で認証ヘッダーが送信されません。私は要求がOPTIONSである場合にのみこの認証を無効にし、他の要求に対してはこのままにします。ここには、私が現時点で持っている設定コードの関連部分があります。なぜそれがうまくいかないのか分からないようです。私はいつもOPTIONSリクエストで401 Unauthorized Errorを取得します。nginx:http要求がOPTIONSの場合にのみ基本認証を要求しない

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 Unauthorizedを取得します。 '場所〜/ fooの/バー/ { 場合($のREQUEST_METHOD = OPTIONS){ ... リターン200; } auth_basic "Restricted"; auth_basic_user_file /var/www/.htpasswd; } ' –

0

それ古い投稿のようですが、この解決策が見つかりました:

次の構成を「location」内に置き、サーバーから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; 
    } 
    } 
関連する問題