Use basic authentication with jQuery and Ajax

前端 未结 10 1080
野的像风
野的像风 2020-11-21 06:11

I am trying to create a basic authentication through the browser, but I can\'t really get there.

If this script won\'t be here the browser authentication will take o

10条回答
  •  时光取名叫无心
    2020-11-21 07:01

    According to SharkAlley answer it works with nginx too.

    I was search for a solution to get data by jQuery from a server behind nginx and restricted by Base Auth. This works for me:

    server {
        server_name example.com;
    
        location / {
            if ($request_method = OPTIONS ) {
                add_header Access-Control-Allow-Origin "*";
                add_header Access-Control-Allow-Methods "GET, OPTIONS";
                add_header Access-Control-Allow-Headers "Authorization";
    
                # Not necessary
                #            add_header Access-Control-Allow-Credentials "true";
                #            add_header Content-Length 0;
                #            add_header Content-Type text/plain;
    
                return 200;
            }
    
            auth_basic "Restricted";
            auth_basic_user_file /var/.htpasswd;
    
            proxy_pass http://127.0.0.1:8100;
        }
    }
    

    And the JavaScript code is:

    var auth = btoa('username:password');
    $.ajax({
        type: 'GET',
        url: 'http://example.com',
        headers: {
            "Authorization": "Basic " + auth
        },
        success : function(data) {
        },
    });
    

    Article that I find useful:

    1. This topic's answers
    2. http://enable-cors.org/server_nginx.html
    3. http://blog.rogeriopvl.com/archives/nginx-and-the-http-options-method/

提交回复
热议问题