我使用react-admin尝试访问Restful API节点服务器。我可以登录,我正在尝试列出用户,但我收到错误401未经授权。
在请求标头中:
authorization: Bearer null
服务器返回错误:
JsonWebTokenError: jwt malformed
在客户端上反应管理数据Provider.js:
const apiUrl = "http://localhost:4000/api/v1";
const token = localStorage.getItem("token");
console.log("Token: " + token);
const httpClient = (url, options = {}) => {
if (!options.headers) {
options.headers = new Headers({ Accept: "application/json" });
}
options.headers.set("Authorization", `Bearer ${token}`);
return fetchUtils.fetchJson(url, options);
};
在服务器auth.js:上
const passport = require('passport');
const httpStatus = require('http-status');
const AppError = require('../utils/AppError');
const { roleRights } = require('../config/roles');
const verifyCallback = (req, resolve, reject, requiredRights) => async (err, user, info) => {
console.log('requiredRights: ' + requiredRights + 'n Info: ' + info + 'n User: ' + user);
if (err || info || !user) {
return reject(new AppError(httpStatus.UNAUTHORIZED, 'Please authenticate'));
}
req.user = user;
if (requiredRights.length) {
const userRights = roleRights.get(user.role);
console.log('userRights: ' + userRights);
const hasRequiredRights = requiredRights.every(requiredRight => userRights.includes(requiredRight));
if (!hasRequiredRights && req.params.userId !== user.id) {
return reject(new AppError(httpStatus.FORBIDDEN, 'Forbidden'));
}
}
resolve();
};
const auth = (...requiredRights) => async (req, res, next) => {
console.log('RES: ' + res);
return new Promise((resolve, reject) => {
passport.authenticate('jwt', { session: false }, verifyCallback(req, resolve, reject, requiredRights))(req, res, next);
})
.then(() => next())
.catch(err => next(err));
};
module.exports = auth;
但有时令牌在请求头中不为空,这是有效的。。。为什么有时令牌为空?
谢谢&问候
Ludo
尝试读取httpClient中的localStorage,如文档中所述:
-const token = localStorage.getItem("token");
console.log("Token: " + token);
const httpClient = (url, options = {}) => {
+ const token = localStorage.getItem("token");
if (!options.headers) {
options.headers = new Headers({ Accept: "application/json" });
}
options.headers.set("Authorization", `Bearer ${token}`);
return fetchUtils.fetchJson(url, options);
};
相关文档:https://marmelab.com/react-admin/Authentication.html#sending-api 的凭据