【问题标题】:NextJS and Auth0 how to get bearer token for api requestsNextJS 和 Auth0 如何获取 api 请求的不记名令牌
【发布时间】:2021-12-23 20:13:24
【问题描述】:

我不知道如何在 fetcher 中将不记名令牌标头添加到我的 API 调用中以接收数据,因为我正在后端检查 JWT 令牌...

提取码:

 const fetcher = async () => {
      const response = await fetch(api); //I need to add bearer token headers to this api request or else it's 401 
      const data = await response.json();

    const props = {
        data: data
      };
  return props;
};

这是数据获取代码

    const {data, error} = useSWR("data", fetcher);
    
      if (error) return <div>oops... {error.message}</div>;
      if (data === undefined) return <div>Loading...</div>;
      console.log(accessToken);
      return <div>{data}</div>;

我在一篇文章中发现了一段代码,说我需要添加这个:

 const {accessToken} = getAccessToken({
    scopes: ["read:shows"], // I don't know what is this scope I just pasted it...
  });

但 accessToken 返回错误,只能在服务器端检索它...

【问题讨论】:

    标签: next.js auth0


    【解决方案1】:

    安装auth0SDK,如果你想解码jwt令牌你需要安装jwt decode lib

    import { getSession, } from '@auth0/nextjs-auth0';
    const jwt = require('jsonwebtoken');
    ...
    //all user data here, with tokens
    const session = getSession(req,res)
    //bearer token here
    const token = session.idToken
    //simple token here
    const tokenId = session.accessToken,
    

    另外,在这个 auth0SDK 中你有很多可以使用的钩子/函数!

    【讨论】:

      【解决方案2】:

      您可以使用任何授权流程来获取不记名令牌

      https://auth0.com/docs/authorization/flows

      【讨论】:

        猜你喜欢
        • 2020-04-13
        • 2016-06-26
        • 2020-12-11
        • 2020-10-18
        • 2019-11-08
        • 2022-12-12
        • 2021-08-13
        • 2021-12-09
        • 2021-03-30
        相关资源
        最近更新 更多