【发布时间】:2020-12-17 19:11:14
【问题描述】:
我正在使用 JWT 来处理身份验证,并且我有一个更新新密码的功能。我的问题是如何在 UpdatePasswordAction 中将此 JWT 传递给我的服务器?实际上,我的 cookie 中有那个 JWT,但是当我将数据提交到服务器时,数据没有正确传递。我通过了吗?
无法从我的服务器检索 JWT。
console.log(JSON.stringify(req.cookies));// -> {}
console.log(req.headers.authorization);// -> undefined
在我的 User.actions.jsx 中,我要做的是获取存储在 cookie 中的令牌并传递包含当前密码、新密码和新确认密码的 updatePasswordState。
import { Cookies } from 'js-cookie';
export const UpdatePasswordAction = (updatePasswordState) => {
return async (dispatch) => {
try {
// what I do is to pass the new password and JWT to the server to handle new password update
const token = Cookies.get('jwt');
const res = await axios.patch(`http://127.0.0.1:3000/users/updateMyPassword`, updatePasswordState, token);
const { data } = res;
dispatch({ type: UserActionTypes.UPDATE_PASSWORD_SUCCESS, payload: data });
alert('Update Password Successfully');
} catch (error) {
if (error.response) {
dispatch({
type: UserActionTypes.UPDATE_PASSWORD_FAIL,
payload: error.response.data.message,
});
console.log(error.response.data.message);
}
}
};
};
在我的服务器中,我有一个中间件来检查用户是否登录。
exports.protect = catchAsync(async (req, res, next) => {
//Getting token and check of it's there
let token;
console.log(JSON.stringify(req.cookies));// -> {}
console.log(req.headers.authorization);// -> undefined
if (
req.headers.authorization &&
req.headers.authorization.startsWith('Bearer')
) {
token = req.headers.authorization.split(' ')[1];
} else if (req.cookies.jwt) {
token = req.cookies.jwt;
}
if (!token) {
return next(
new AppError('You are not logged in! Please log in to get access.', 401)
);
}
// rest jwt decode and verification
});
有什么办法吗?
【问题讨论】: