React Native jwtDecode - InvalidTokenError:Invalid token specified:invalid base64 for part #2(Property 'atob' doesn't exist)]

l3zydbqr  于 5个月前  发布在  React
关注(0)|答案(1)|浏览(91)

所以我在Code with Mosh上学习了一门关于React Native的在线课程,尽管有些东西已经过时了,我不得不寻找工作,但一切都很顺利。直到我到达最后一章,当谈到身份验证和授权时。我们有一个预制的小型服务器,我们在本地托管,它为用户设置了JWT令牌系统,这一切都很好。我们做了一个POST,在那里我们发送了注册的电子邮件和密码,并得到了一个令牌。使用jwt.io,我们可以解码令牌并获得所有的信息。然而,当我尝试使用jwt-decode解码它时,我只是得到了这个错误消息,我无法理解为什么。
TLDR,令牌可以通过jtw.io等网站在线解码,但安装和使用jtw-decode只是给我这个消息。
下面是我的代码:(我跳过了一些与问题无关的东西。

import React, { useState, useContext } from "react";
import { Image, StyleSheet } from "react-native";
import \* as Yup from "yup";
import { jwtDecode } from "jwt-decode";

const handleSumbit = async ({ email, password }) =\> {
const result = await authApi.login(email, password);
if (!result.ok) return setLoginFailed(true);
setLoginFailed(false);

const token = result.data;
const decoded = jwtDecode(token);
console.log(decoded);
};

字符串

预期输出:

第一个月

实际产量:

Warning: An unhandled error was caught from submitForm() \[InvalidTokenError: Invalid token specified: invalid base64 for part #2 (Property 'atob' doesn't exist)\]

  • 我尝试直接记录令牌,而不是记录到const中。
  • 我试过另一个解码器,我发现,发生了类似的问题。
  • 我已经在jwt.io上记录了令牌并手动解码,它在那里工作没有问题。
igsr9ssn

igsr9ssn1#

你需要使用类似core-js的东西来poly-fill atob函数。
1.使用core-js

import "core-js/stable/atob";
import { jwtDecode } from "jwt-decode";

const token = "eyJ0eXAiO.../// jwt token";
const decoded = jwtDecode(token);

console.log(decoded);

字符串
1.使用base-64

import { decode } from "base-64";

global.atob = decode;


你的代码可能看起来像这样:

import React, { useState, useContext } from "react";
import { Image, StyleSheet } from "react-native";
import * as Yup from "yup";
import { jwtDecode } from "jwt-decode";
import "core-js/stable/atob"; // <- polyfill here

const handleSumbit = async ({ email, password }) => {
  const result = await authApi.login(email, password);

  if (!result.ok) return setLoginFailed(true);

  setLoginFailed(false);

  const token = result.data;
  const decoded = jwtDecode(token);
  
  console.log(decoded);
};

参考资料:https://github.com/auth0/jwt-decode#polyfilling-atob

相关问题