繁体   English   中英

无法使用AngularJS验证REST API

[英]Can't authenticate REST API with AngularJS

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

我正在尝试使用AngularJS $http对资源进行身份验证。 我的Flask后端非常简单,并使用装饰器进行设置以处理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'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM