无法使用 AngularJS 验证 REST API

Can't authenticate REST API with AngularJS

我正在构建一个带有 AngularJS 前端和 Flask REST API 后端的应用程序。

我正在尝试使用 AngularJS $http 对资源进行身份验证。我的 Flask 后端非常简单,并设置了 this 装饰器来处理 CORS。

我在 Flask 中的基本视图代码如下所示:

@auth.verify_password
def verify_password(username, password):
    # for now, I just want to see the correct credentials are present
    print 'credentials: %s %s' % (username, password)
    return True

@app.route('/login')
@cross_origin('http:/localhost')
@auth.login_required
def index():
    return jsonify({'auth': str(request.authorization)})

这适用于我的本地开发环境,所以当我这样做时

curl -u myusername:mypassword http://127.0.0.1:5000/login

我得到了预期的结果:

* About to connect() to 127.0.0.1 port 5000 (#0)
*   Trying 127.0.0.1...
* connected
* Connected to 127.0.0.1 (127.0.0.1) port 5000 (#0)
* Server auth using Basic with user 'myusername'
> GET /login HTTP/1.1
> Authorization: Basic am9objpoZWxsbw==
> User-Agent: curl/7.26.0
> Host: 127.0.0.1:5000
> Accept: */*
> 
* additional stuff not fine transfer.c:1037: 0 0
* HTTP 1.0, assume close after body
< HTTP/1.0 200 OK
< Content-Type: application/json
< Content-Length: 20
< Access-Control-Allow-Origin: http://localhost
< Access-Control-Allow-Methods: HEAD, OPTIONS, GET
< Access-Control-Max-Age: 21600
< Access-Control-Allow-Credentials: true
< Access-Control-Allow-Headers: authorization
< Vary: Origin
< Server: Werkzeug/0.10.1 Python/2.7.3
< Date: Mon, 09 Mar 2015 17:37:27 GMT
{
  "auth": "{'username': 'myusername', 'password': 'mypass'}"
  * Closing connection #0
}

在我的 AngularJS 应用程序中,我想做同样的事情,所以我有一个身份验证服务:

myApp

  .service('AuthService', function ($http, $rootScope, $state) {
    return {
      login: function (credentials) {
        console.log('credentials', credentials); // credentials are correct
        return $http
          .get('http://127.0.0.1:5000/login', credentials)
          .then(function (result) {
            // do something
            console.log('result', result);
          });
        },
        ...
     }
  })

我也配置$http:

// CORS
$httpProvider.defaults.useXDomain = true;
$httpProvider.defaults.withCredentials = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
$httpProvider.defaults.headers.common["Accept"] = "application/json";
$httpProvider.defaults.headers.common["Content-Type"] = "application/json";

当我使用 curl 检查请求详细信息时,我可以清楚地看到用户名和密码已通过。但是,当使用 AngularJS 时,Flask 中的 request.authorization 对象是空的,这意味着没有凭据或者它们在错误的位置。

如何在 AngularJS 中正确传递凭据?

我认为你需要:

 $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w'