Use basic authentication with jQuery and Ajax

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

    
        AuthUserFile /path/to/.htpasswd
        AuthType Basic
        AuthName "Whatever"
        Require valid-user
    
    
    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.

提交回复
热议问题