我正在使用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中正确传递凭据?
答案 0 :(得分:1)
我认为你需要:
$http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w'