Javascript 在Chrome中使用jquery隐藏基本身份验证弹出窗口

Javascript 在Chrome中使用jquery隐藏基本身份验证弹出窗口,javascript,jquery,ajax,google-chrome,Javascript,Jquery,Ajax,Google Chrome,我将此代码用于REST API的基本认证。不幸的是,当用户/密码错误时,Google Chrome会显示一个弹出窗口。Firefox没有做到这一点 $.ajax({ type: "GET", url: "/ad", dataType: 'json', async: false, username: 'username', password: 'password', success: function (){ alert('s

我将此代码用于REST API的基本认证。不幸的是,当用户/密码错误时,Google Chrome会显示一个弹出窗口。Firefox没有做到这一点

$.ajax({
    type: "GET",
    url: "/ad",
    dataType: 'json',
    async: false,
    username: 'username',
    password: 'password',
    success: function (){
        alert('success');
        return false;
    },
    error: function(){
        alert('error');
        return false;
    }
});
编辑1:


我使用Laravel框架

我认为您可以在URL中传递用户名和密码,而不是HTTP身份验证。 试一试:

$.ajax({
    type: "GET",
    url: "http://username:password@whatever.com/ad",
    dataType: 'json',
    async: false,
    success: function (){
        alert('success');
        return false;
    },
    error: function(){
        alert('error');
        return false;
    }
});

我认为您可以在URL中传递用户名和密码来代替HTTP身份验证。 试一试:

$.ajax({
    type: "GET",
    url: "http://username:password@whatever.com/ad",
    dataType: 'json',
    async: false,
    success: function (){
        alert('success');
        return false;
    },
    error: function(){
        alert('error');
        return false;
    }
});

如果您没有服务器控制权,就没有(至少我不知道)方法来防止这种情况。如果您拥有服务器控制权,您可以做两件事:

  • 将响应状态代码从标准401更改为其他代码。但是,这通常不是最佳做法,因为状态代码不会说明实际问题(身份验证错误)

  • 将响应头
    WWW-Authenticate:Basic realm=“your\u realm”
    更改为自定义值,如
    WWW-Authenticate:x-Basic realm=“your\u realm”
    (注意那里的
    x-

  • 这将阻止任何默认登录处理

    更新1

    至于使用Laravel,可以作为设置正确响应标题的示例
    WWW-Authenticate
    (将
    Basic
    更改为
    x-Basic
    ):

    Route::filter('auth',function())
    {
    $credentials=['email'=>Request::getUser(),'password'=>Request::getPassword()];
    如果(!Auth::once($credentials)){
    $response=['error'=>true,'message'=>Unauthorized request'];
    $code=401;
    $headers=['WWW-Authenticate'=>'x-Basic'];
    返回响应::json($Response,$code,$headers);
    }
    });
    
    如果您没有服务器控制权,就没有(至少我不知道)方法来防止这种情况发生。如果您拥有服务器控制权,您可以做两件事:

  • 将响应状态代码从标准401更改为其他代码。但是,这通常不是最佳做法,因为状态代码不会说明实际问题(身份验证错误)

  • 将响应头
    WWW-Authenticate:Basic realm=“your\u realm”
    更改为自定义值,如
    WWW-Authenticate:x-Basic realm=“your\u realm”
    (注意那里的
    x-

  • 这将阻止任何默认登录处理

    更新1

    至于使用Laravel,可以作为设置正确响应标题的示例
    WWW-Authenticate
    (将
    Basic
    更改为
    x-Basic
    ):

    Route::filter('auth',function())
    {
    $credentials=['email'=>Request::getUser(),'password'=>Request::getPassword()];
    如果(!Auth::once($credentials)){
    $response=['error'=>true,'message'=>Unauthorized request'];
    $code=401;
    $headers=['WWW-Authenticate'=>'x-Basic'];
    返回响应::json($Response,$code,$headers);
    }
    });
    
    谢谢您的回答。然而,这并不会改变你的答案。但是,这对meIs来说没有任何改变。在symfony中可以这样做吗?在symfony中可以这样做吗?