NodeJS 为什么jsonwebtoken声明我的token无效?

zsbz8rwp  于 12个月前  发布在  Node.js
关注(0)|答案(1)|浏览(131)

在客户机上,我有以下函数,它调用服务器API来注册一个用户。

public register = (user) => {
    this.httpClient.post<User>(this.url, user).pipe(
      tap(userData => {
        console.log('userData register.userData', userData)
        localStorage.setItem('userToken', JSON.stringify(userData.token));
        // this.router.navigate(['/home']);
      })
    ).subscribe(),
    catchError(error => {
      console.log('error', error)
      this.store.dispatch(messageActions.SetError({error}))
      throw error;
    })
  }

字符串
这里可以看到令牌的副本:
“eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI2NTRkNzc4MzFkMGUxN2ZiZTI1MDMyM2EiLCJpYXQiOjE2OTk1NzU3ODQsImV4cCI6MTY5OTU3NzU4NH0.3HsdFjARnAjWn35_VlXsJQ6oFbfL_3OLHTPsroIOayU”
拦截器将令牌附加到每个请求的头部,如下所示:

intercept(request: HttpRequest<unknown>, next: HttpHandler): 
Observable<HttpEvent<unknown>> {
   const token = localStorage.getItem('userToken');
   console.log('token', token)

   if(token) {
    // const authReq = req.clone({setHeaders:{token:token}});

    const authReq = request.clone({setHeaders:{"Authorization":"Bearer " + token}});

    console.log('authReq', authReq)
    return next.handle(authReq)
}

    return next.handle(request);
  }
}


以下是服务器端与创建令牌相关的精简代码:

exports.register = async (req, res) => {
    try {
        let userData = {};
        userData.token = generateAccessToken(newUser._id);
        userData.cart = cart;

       console.log("userData", userData);

        return res.status(201).json(userData)

    } catch (error) {
        console.log(error);
        res.status(500).send('Problem signing up user!')
        // throw error;

    }
};

function generateAccessToken(userId) {
    return jwt.sign({ userId }, process.env.JWT_SECRET, { expiresIn: '1800s' });
}

function authenticateToken(req, res) {
    const authHeader = req.headers.authorization
    console.log('authHeader', authHeader)
    const token = authHeader && authHeader.split(' ')[1]
    console.log('token', token)

    try {
        if (token == null) return res.status(500).send('Problem authenticating user token.')

         const {
            userId
        } = jwt.verify(token, process.env.JWT_SECRET)

        return userId;
    
   } catch(err) {
       console.log(err);
        res.status(500).send('Problem authenticating user token.')
    }
}


这是从拦截器传输到服务器的令牌的副本。(当然,“承载者”被剥离了。
“eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI2NTRkNzc4MzFkMGUxN2ZiZTI1MDMyM2EiLCJpYXQiOjE2OTk1NzU3ODQsImV4cCI6MTY5OTU3NzU4NH0.3HsdFjARnAjWn35_VlXsJQ6oFbfL_3OLHTPsroIOayU”
当调用jwt.verify时,authenticateToken函数出错,并显示消息:Invalid token。

z31licg0

z31licg01#

localStorage.setItem('userToken', JSON.stringify(userData.token));

字符串
您使用JSON.stringify()存储令牌,但在检索令牌时没有使用JSON.parse()
它将嵌入"字符来 Package 实际的令牌。

const token = "my-jwt-token";

console.log("compare");
console.log({ Authorization: `Bearer ${token}` });
console.log({ Authorization: `Bearer ${JSON.stringify(token)}` });


考虑到令牌只是一个字符串,我不会使用JSON.stringify()

localStorage.setItem('userToken', userData.token);

相关问题