Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/455.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用js客户机在需要身份验证的Flask restful api中执行某些方法_Javascript_Ajax_Rest_Authentication_Flask - Fatal编程技术网

Javascript 如何使用js客户机在需要身份验证的Flask restful api中执行某些方法

Javascript 如何使用js客户机在需要身份验证的Flask restful api中执行某些方法,javascript,ajax,rest,authentication,flask,Javascript,Ajax,Rest,Authentication,Flask,因此,我正在创建一个简单的js客户端应用程序,以实现完整的api 我有一些需要用户身份验证的方法,但是即使我登录到服务器,我也不能调用它们,得到401错误,未经授权 这些是登录到flask服务器的代码 身份验证方法,其中保存用户 @auth.verify_password def verify_password(email, password): user = User.query.filter_by(email=email).first() if not user:

因此,我正在创建一个简单的js客户端应用程序,以实现完整的api 我有一些需要用户身份验证的方法,但是即使我登录到服务器,我也不能调用它们,得到401错误,未经授权

这些是登录到flask服务器的代码

身份验证方法,其中保存用户

@auth.verify_password
def verify_password(email, password):
    user = User.query.filter_by(email=email).first()
    if not user:
        return False
    g.user = user
    return flask_bcrypt.check_password_hash(user.password, password)
身份验证视图(请求后)

会议形式

class SessionCreateForm(Form):
    email = StringField('email', validators=[DataRequired()])
    password = StringField('password', validators=[DataRequired()])
JS客户端(登录功能)Ajax post请求

    function logar () {

        var lform = $('#loginform').serializeArray();

        login = lform[0].value;
        password = lform[1].value;

        $.ajax
        ({  
            type: "POST",
            url: "http://localhost:5000/api/v1/sessions",
            data: {email: login, password: password},
        })
        .success(function(result)
        {
            // logou
            $.cookie("user", login);

            console.log(result);

            window.location.replace("index.html");
        })
        .error(function(result)
        {
            alert("Not Authorized!");
        });

    }
当我登录到服务器时,我无法执行这些功能

class PurchaseView(restful.Resource):
    @auth.login_required
    def post(self):
        form = PurchaseCreateForm()
        if not form.validate_on_submit():
            return form.errors, 422
        purchase = Purchase(form.total.data)

        g.purchase = purchase

        db.session.add(purchase)
        db.session.commit()
        return PurchaseSerializer(purchase).data, 201
我在这个ajax电话中得到了401

        $.ajax
        ({
            type: "POST",
            url: "http://localhost:5000/api/v1/purchase",
            data: {total: cart.total},
        })
        .success(function(result)
        {
            console.log(result);

        })
        .error(function(result)
        {
            alert("Error");
        });
资源

api.add_resource(UserView, '/api/v1/users')
api.add_resource(SessionView, '/api/v1/sessions')
api.add_resource(ProductListView, '/api/v1/products')
api.add_resource(ProductUpdateView, '/api/v1/product_update')
api.add_resource(PurchaseProductView, '/api/v1/purchase_product')
api.add_resource(PurchaseView, '/api/v1/purchase')
api.add_resource(ProductView, '/api/v1/products/<int:id>')

这是因为您需要发送授权标头,因为该端点受到保护。在本教程中,它使用基本身份验证,登录端点仅用于检查电子邮件和密码是否正确(当您的客户端应用程序具有登录页面并且需要在将登录凭据保存到客户端存储(如localStorage)中之前验证登录凭据是否正确时,此功能非常有用)。客户端应用程序仍然负责在每个需要身份验证的请求上发送授权头。您将在本教程的第二部分中看到-

它会在每个请求上发送授权标头。最好检查客户端存储中是否存在凭据,如果存在,则通过授权标头发送凭据

我建议您首先阅读有关基本身份验证的内容


希望有帮助。

那么,有没有办法通过服务器应用程序返回authToken?
api.add_resource(UserView, '/api/v1/users')
api.add_resource(SessionView, '/api/v1/sessions')
api.add_resource(ProductListView, '/api/v1/products')
api.add_resource(ProductUpdateView, '/api/v1/product_update')
api.add_resource(PurchaseProductView, '/api/v1/purchase_product')
api.add_resource(PurchaseView, '/api/v1/purchase')
api.add_resource(ProductView, '/api/v1/products/<int:id>')
curl 'http://localhost:5000/api/v1/purchase' -H 'Origin: http://localhost:8000' -H 'Accept-Encoding: gzip, deflate' -H 'Accept-Language: en-US,en;q=0.8,es;q=0.6,pt;q=0.4' -H 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.76 Safari/537.36' -H 'Content-Type: application/x-www-form-urlencoded; charset=UTF-8' -H 'Accept: */*' -H 'Referer: http://localhost:8000/checkout.html' -H 'Connection: keep-alive' --data 'total=40' --compressed


HTTP/1.0 401 UNAUTHORIZED
Content-Type: text/html; charset=utf-8
Content-Length: 19
WWW-Authenticate: Basic realm="Authentication Required"
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: Content-Type,Authorization
Access-Control-Allow-Methods: GET,PUT,POST,DELETE
Server: Werkzeug/0.9.6 Python/2.7.6
Date: Mon, 09 Mar 2015 03:09:44 GMT
headers['Authorization'] = 'Basic ' + AuthService.getToken();