【问题标题】:HTTP Basic Authentication in AngularJSAngularJS 中的 HTTP 基本身份验证
【发布时间】:2018-08-08 21:50:19
【问题描述】:

我正在尝试调用 AngularJS 中的 API。 API 有 HTTP Basic Authenticationusername = adminpassword = admin123

这就是我调用 API 的方式,

$http.get('https://example.com', {
    headers: {'Authorization': 'Basic YWRtaW46YWRtaW4xMjM='}
}).then(console.log("something"));

但是,它给了我401 UnAuthorized 的响应。传递用户名和密码的推荐方式是什么?我正在使用AngularJS 1

显示错误,

OPTIONS https://example.com 401 ()

Failed to load https://example.com: Response for preflight has invalid HTTP status code 401.

Possibly unhandled rejection: {"data":null,"status":-1,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","headers":{"Authorization":"Basic YWRtaW46YWRtaW4xMjM=","Accept":"application/json, text/plain, */*"},"url":"https://example.com"},"statusText":"","xhrStatus":"error"}

【问题讨论】:

    标签: javascript angularjs http basic-authentication


    【解决方案1】:

    如果您的所有请求都需要授权标头,您可能希望将授权标头设置在更全局的级别。您可以通过添加来做到这一点

    .config(['$httpProvider', function($httpProvider) {
        $httpProvider.defaults.headers.common['Authorization'] = '<Basic Auth Header>';
    }]);
    

    在您的应用配置中。为了回答您的实际问题,我认为您提供的代码没有任何特别的问题。您能否提供一些关于服务器端期望什么以及它如何读取授权的信息?

    【讨论】:

    • 从错误信息来看,API 似乎只采用了 Option 方法。我正在使用 GET。有问题吗?
    • 我已经更新了错误日志。请检查。每当您点击 URL 时,它都会以简单的登录表单询问用户名和密码
    • 您确定您使用的凭据是正确的吗?您也可以尝试使用 CURL 之类的命令在命令行中发出请求,以查看是服务器问题还是 Angular 客户端代码问题。
    • 通过 https 进行身份验证时,NGINX 或其他网络服务器会丢弃查询字符串身份验证;尝试以某种方式将queryStringAuth: true 添加到您的请求中。
    猜你喜欢
    • 2015-09-09
    • 2019-01-07
    • 1970-01-01
    • 1970-01-01
    • 2021-03-21
    • 2011-11-12
    • 2011-05-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多