javascript - 验证前端应用程序和后端 REST API

标签 javascript rest api express

<分区>

我已经为客户端 开发了一个REST API 和应用程序逻辑。现在,应用程序逻辑和 REST API 都是分离的,没有紧密耦合。

我想实现一个身份验证系统,这样在从client-side 登录后,您将在client-side 上自动进行身份验证>REST API 端。

示例:登录客户端后,用户可以访问photo/addapi/photo/add 自动。

我想使用 cookies 但我不知道它是否可行,我想尝试 JWT 但到目前为止我读到的只是解决 client-sidefront-end 其中应用程序逻辑和对数据库的调用紧密耦合REST API单独使用,但不能同时使用。

简而言之:我是说我当时如何对页面和REST API等 View 进行身份验证?

最佳答案

要在您的客户端和 API 之间进行通信,您可以使用 AJAX , 为此你可以使用

the fetch API

fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => {  
    if (!response.ok) {
      // error handling
      throw new Error('HTTP error, status = ' + response.status);
    }
    return response.json();
  })
  .then(json => console.log(json))

HMLHttpRequest

let xhttp = new XMLHttpRequest()
xhttp.open('GET', 'https://jsonplaceholder.typicode.com/posts/1', false); 
xhttp.onreadystatechange = function(event) {
    // XMLHttpRequest.DONE === 4
    if (this.readyState === XMLHttpRequest.DONE) {
        if (this.status === 200) {
            // worked
            console.log(this.responseText);
        } else {
            // error
            console.log("Status de la réponse: %d (%s)", this.status, this.statusText);
        }
    }
};
xhttp.send(null);


可以使用 cookie 或 session 存储来保持连接

主要区别是 cookie 是作为每个请求的 HTTP header 发送的,而 localstorage 只能通过您的客户端 js 访问

cookie可以在 js 中使用 document.cookie 访问,它给出一个看起来像 name=oeschger 的字符串;最喜欢的食物=牛肚; test1=你好; test2=世界

localStorage可以通过 window.localStorage 访问,这是一个 Storage提供 5 个方法的对象:

  • Storage.key() 当传递一个数字 n 时,该方法将返回存储中第 n 个键的名称。

  • Storage.getItem() 当传递一个键名时,将返回该键的值。

  • Storage.setItem() 当传递一个键名和值时,将该键添加到存储中,或者更新该键的值(如果它已经存在)。

  • Storage.removeItem() 传递 key 名称时,将从存储中删除该 key 。

  • Storage.clear() 调用时,将清空存储中的所有 key 。

保持登录状态的方法

它们用于自动登录的方式是:

  • 你看看是否有库存的授权 token (随机唯一字符串)
  • 如果是,您尝试使用 token 登录
    • 如果服务器接受一切正常
    • 如果服务器拒绝你去else
  • 其他
    • 用户正常登录帐号
    • 服务器用授权 token 回答
    • 你可以按照你想要的方式存储它

auth token 必须有一个有限的生命周期(cookies 在欧洲超过一年是违法的)

每个账户最多一个 token ,新 token 会使之前的 token 无效

有关 https://security.stackexchange.com/ 过程的更多信息

关于javascript - 验证前端应用程序和后端 REST API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57411969/

相关文章:

javascript - ReactJS 中的 Bootstrap 行

javascript - 使用 icomoon 将 SVG 转换为字体图标

android - 带有 Android Retrofit V2 库的 AWS S3 Rest API,上传的图像已损坏

rest - axis2/c 中创建的 Restful Web 服务真的是 RESTful 吗?

python - 如何在flutter中从本地主机上运行的服务器获取数据?

android - API 16 上的网站与较新的 API 相比看起来很糟糕

javascript - 使用 zone.js 从任何地方检测当前执行上下文?

javascript - 做一些 ajax 并使用 getJSON 返回一个 promise

java - Gson:预期为 begin_array,但为 STRING 如何控制它

regex - Jax-RS 重载方法/路径执行顺序