我已经为客户端
开发了一个REST API
和应用程序逻辑。现在,应用程序逻辑和 REST API
都是分离的,没有紧密耦合。
我想实现一个身份验证系统,这样在从client-side
登录后,您将在client-side
和 上自动进行身份验证>REST API
端。
示例:登录客户端
后,用户可以访问photo/add
和api/photo/add
自动。
我想使用 cookies
但我不知道它是否可行,我想尝试 JWT
但到目前为止我读到的只是解决 client-side
或 front-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/ 过程的更多信息