简体   繁体   English

从JavaScript调用API的安全方法?

[英]Secure way to call the API from Javascript?

I'm using flask to build my API. 我正在使用flask建立我的API。 I've a tornado server in front of flask which takes care of requests. 我在烧瓶前面有一个龙卷风服务器,负责处理请求。 I'm using HTTP basic auth in Flask like this: 我在Flask中使用HTTP基本身份验证,如下所示:

auth = HTTPBasicAuth()

@auth.get_password
def get_password(username):
    if username == 'uname':
        return 'password'
    return None

And this is how I'm calling the API from my Javascript: 这就是我从Javascript调用API的方式:

$.ajax({
            url: api_url + 'customer',
            type: 'GET',
            dataType: 'json',
            async: false,

            headers: {
                "Authorization": "Basic " + btoa(uname + ":" + password)
            },

            data: {start: start_date, end: end_date},
            success: function(result) {
                data = result.results;
            }
         });

I realize that this isn't exactly secure (since the front end JS file has "username" and "password" in it) so my question is how do I make it secure? 我意识到这不是完全安全的(因为前端JS文件中包含“用户名”和“密码”),所以我的问题是如何使它安全? What's the correct way to make API requests? 发出API请求的正确方法是什么?

You cant avoid sending your password this way and it's fine. 您无法避免以这种方式发送密码,这很好。 You just need to take reasonable precautions about how those credentials are handled. 您只需要采取合理的预防措施来处理这些凭据。 Make sure you are not saving the password in cookies / localStorage. 确保您未将密码保存在cookie / localStorage中。

Make sure the uname and password variables are not hard-coded into the source code. 确保unamepassword变量未硬编码到源代码中。 Those should be passed by user input via form. 这些应该由用户通过表单输入。

As long as the password is only in memory, you should be safe if you protect yourself from XSS attacks. 只要密码仅在内存中,就可以保护自己免受XSS攻击。

I also strongly encourage you to use HTTPS connection to the server. 我也强烈建议您使用与服务器的HTTPS连接。

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

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