令牌在终结点生成,但不会到达页面 [英] Token is generated at the endpoint but does not arrive on the page

查看:0
本文介绍了令牌在终结点生成,但不会到达页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用Svelte/Kit和JWT创建一个网站。 我在互联网上找到了相关说明,例如: Svelte JWT身份验证https://morioh.com/p/1d95522418b2 使用Cookie的SvelteKit会话身份验证https://www.youtube.com/watch?v=bG7cxwBMVag 但不幸的是,没有关于Svelte Kit和JWT的说明。所以我亲自试了试。

令牌在终结点生成,但不会到达页面(或不可调用)。我怀疑标题中的某些设置是错误的,但找不到错误的地方。这是我高度简化的测试环境:

(1)我从页面index.svelte调用端点login.js。为了进行测试,我省略了检查电子邮件和密码,并立即将JWT发送回来。数据已到达,但我没有看到JWT。

(2)应将JWT发送到另一个终结点。执行此操作的最佳方式是什么?

第&q;页index.svelte(简体):

<script>
  let email="", password="";
    
  const doLogin = async () => {
    const response = await fetch("/auth/login", {
      method: 'POST',
      headers: {
    "Content-Type": "application/json",
      },
      credentials: 'include',
      body: JSON.stringify({
    email,
    password
      })
    }); 
    
    if (response.status == 200) {
      const { done, value } = 
        await response.body.getReader().read();
      await console.log("done, value=", done, 
        JSON.parse(new TextDecoder("utf-8").decode(value)));
      await console.log("headers=", response.headers);
    }
  }
</script>

<h1>Welcome to MyAuth</h1>
<input type=email bind:value={email}/><br/>
<input type=password bind:value={password}/><br/>
<button on:click={doLogin}>Submit</button>

终结点";login.js(简化):

import jwt from "jsonwebtoken";  

export function post(request, context) {
  const token = jwt.sign({
    data: { text: "test" },
    "topsecret", 
  });  
    
  const response = {
    status: 200,
    headers: {
      'content-type': 'application/json',
      'Authorization': `Bearer ${token}`,
    },
    body: {
      passwordOk: true,
    }
  };
  return response;
}

控制台显示:

done, value= false {passwordOk: true}
index.svelte:59 headers= Headers {}
index.svelte:44 Fetch finished loading: POST "http://localhost:3000/auth/login".
doLogin @ index.svelte:44

推荐答案

我认为您混淆了身份验证的两个主要部分:

  1. 请求/发送凭据。
  2. 使用这些凭据访问受保护的内容。

Authorization: Bearer ${token}通常从(浏览器)客户端发送到服务器,以请求访问受保护的内容。因此,现在,您的服务器正在向客户端请求许可。这没有意义。

相反,登录终结点应通过以下方式发送令牌:

  • Set-Cookie登录终结点中的标头。
  • 响应的body(其中passwordOk是)。

Set-Cookie使浏览器将此值作为Cookie与将来的每个请求一起发送。服务器可以在提供受保护内容之前检查此Cookie值。这可以更安全,因为您可以仅发送HTTP Cookie。

如果令牌是在登录响应的正文中发送的,则客户端应该在以后的请求中使用Authorization: Bearer ${token}头发送令牌。然后,服务器可以在提供受保护内容之前检查此标头。

这篇关于令牌在终结点生成,但不会到达页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆