【问题标题】:Connecting js frontend to fastapi application - authentication problem将 js 前端连接到 fastapi 应用程序 - 身份验证问题
【发布时间】:2021-07-09 23:04:18
【问题描述】:

我按照https://fastapi.tiangolo.com/tutorial/security/oauth2-jwt/ 中描述的步骤进行了复制粘贴。

我有一个登录页面,格式如下:

...
<form class="login_form" id="login_form">
  <div class="username_div">
    <input type="text" id="username_id" name="username" placeholder="Username"><br>
  </div>
  <div class="password_div">
    <input type="password" id="password_id" name="password" placeholder="Password">
  </div>
  <div class="btn_div">
    <input type="button" id="btn_id" value="Login" class="login_btn" onclick="token()">
  </div>
</form>
...

我有一个可以成功获取token的js文件:

function token() {
    fetch('/token', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: 'username=test&password=test'
    }).then(res => {
        return res.json();
    }).then(json => {
        console.log(json['access_token']);
    });
}

现在当我添加

window.location.href = "/users/me/";

console.log(json['access_token]); 之后,我得到一个“未通过身份验证”。

据我了解,我需要以某种方式将令牌传递给 fastapi 部分。我该怎么做?

编辑:

所以我在这里搞混了几件事。但我现在可以使用以下代码打印用户数据:

function token() {
    fetch('/token', {
        method: 'POST',
        headers: {
            'accept': 'application/json',
            'Content-Type': 'application/x-www-form-urlencoded'
        },
        body: 'grant_type=&username=test&password=test&scope=&client_id=&client_secret='
    }).then(res => {
        return res.json();
    }).then(json => {
        console.log(json['access_token']);
        fetch('/users/me', {
            method: 'GET',
            headers: {
                'accept': 'application/json',
                'Authorization': 'Bearer ' + json['access_token']
            }
        }).then(res => {
            return res.json();
        }).then(json => {
            console.log(json);
        });
    });
}


在登录页面中添加凭据后,我仍然不知道如何进入新页面(需要授权)。你能帮帮我吗?

【问题讨论】:

  • 你在哪里添加window.location.href?此外,这用于从一个页面导航到另一个页面。最后但并非最不重要的一点是,您将令牌存储在哪里?在该功能中,您仅在屏幕上打印访问令牌。您需要它向服务器发送更多请求
  • > 你在哪里添加window.location.href? |在最后一个 .then() | 结束的 token 函数中> 用于从一页导航到另一页 |我知道,我想在登录后重定向到下一页 | > 你在哪里存储令牌 |现在我只想将令牌存储在浏览器内存中,所以没有 cookie、本地或会话存储
  • 如果您不将其存储在 cookie 或会话中,服务器如何判断您是否是同一用户?基本上,您在不提供访问令牌的情况下登录、获取令牌、丢弃令牌并导航到另一个页面
  • 据我了解,post(选项 4)说我可以使用内存中的令牌。我还编辑了我的问题。我现在知道如何使用fetch 对自己进行授权,但是当我想访问 html 页面时该怎么做呢?
  • 取决于您使用的是什么。最后,cookie是最简单的方法。否则,使用 fetch 获取每个页面

标签: javascript html authentication frontend fastapi


【解决方案1】:

因此,根据post,无法向重定向添加自定义标头。看来我需要使用 cookie。

非常感谢@Isabi。

【讨论】:

    猜你喜欢
    • 2022-09-27
    • 1970-01-01
    • 2015-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-23
    • 1970-01-01
    相关资源
    最近更新 更多