Use basic authentication with jQuery and Ajax

前端 未结 10 1059
野的像风
野的像风 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:00

    Use the jQuery ajaxSetup function, that can set up default values for all ajax requests.

    $.ajaxSetup({
      headers: {
        'Authorization': "Basic XXXXX"
      }
    });
    
    0 讨论(0)
  • 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/
    0 讨论(0)
  • 2020-11-21 07:04

    Use the beforeSend callback to add a HTTP header with the authentication information like so:

    var username = $("input#username").val();
    var password = $("input#password").val();  
    
    function make_base_auth(user, password) {
      var tok = user + ':' + password;
      var hash = btoa(tok);
      return "Basic " + hash;
    }
    $.ajax
      ({
        type: "GET",
        url: "index1.php",
        dataType: 'json',
        async: false,
        data: '{}',
        beforeSend: function (xhr){ 
            xhr.setRequestHeader('Authorization', make_base_auth(username, password)); 
        },
        success: function (){
            alert('Thanks for your comment!'); 
        }
    });
    
    0 讨论(0)
  • 2020-11-21 07:12

    As others have suggested, you can set the username and password directly in the Ajax call:

    $.ajax({
      username: username,
      password: password,
      // ... other parameters.
    });
    

    OR use the headers property if you would rather not store your credentials in plain text:

    $.ajax({
      headers: {"Authorization": "Basic xxxx"},
      // ... other parameters.
    });
    

    Whichever way you send it, the server has to be very polite. For Apache, your .htaccess file should look something like this:

    <LimitExcept OPTIONS>
        AuthUserFile /path/to/.htpasswd
        AuthType Basic
        AuthName "Whatever"
        Require valid-user
    </LimitExcept>
    
    Header always set Access-Control-Allow-Headers Authorization
    Header always set Access-Control-Allow-Credentials true
    
    SetEnvIf Origin "^(.*?)$" origin_is=$0
    Header always set Access-Control-Allow-Origin %{origin_is}e env=origin_is
    

    Explanation:

    For some cross domain requests, the browser sends a preflight OPTIONS request that is missing your authentication headers. Wrap your authentication directives inside the LimitExcept tag to respond properly to the preflight.

    Then send a few headers to tell the browser that it is allowed to authenticate, and the Access-Control-Allow-Origin to grant permission for the cross-site request.

    In some cases, the * wildcard doesn't work as a value for Access-Control-Allow-Origin: You need to return the exact domain of the callee. Use SetEnvIf to capture this value.

    0 讨论(0)
提交回复
热议问题