Ovi*_*u G 1 express jwt reactjs passport.js redux
我正在使用带有 jwt 的passport.js 来验证我的应用程序中的用户。我正在使用包含其他字段和头像字段的有效负载签署 jwt 令牌,以便在我的应用程序中使用头像。现在,我希望用户能够编辑他们的头像。我实现了这个功能并且在一个问题上工作得很好:即使在 mongodb 中更新了头像字段,但只有在我注销并重新登录后,更改才会显示在应用程序中。(再次重新签名令牌后)
在前端,我使用的是 react + redux。
考虑到这是有效载荷的一部分,我应该如何以正确的方式更新此头像字段?我应该使用另一种方法吗?
代码如下:
登录登录如下:
User.findOne({ email: email }).then(user => {
if (!user) {
return res.status(404).json({
email: "Couldn't find an account."
});
} else {
bcrypt.compare(password, user.password).then(isMatch => {
if (isMatch) {
//User matched
//Create JWT Payload (can contain any user info)
const payload = {
id: user.id,
firstname: user.firstname,
lastname: user.lastname,
email: user.email,
avatar: user.avatar
};
//Sign token
//The sign method from jwt needs a payload(user info), secret and optional expiration date
//This token is needed so the user can access private routes or any other private logic
jwt.sign(
payload,
keys.secretOrKey,
{ expiresIn: "1d" },
(err, token) => {
res.json({
success: true,
token: "Bearer " + token
});
}
);
} else {
return res
.status(400)
.json({ password: "Eroare! Parola incorecta!" });
}
});
}
});
});
Run Code Online (Sandbox Code Playgroud)
还原动作:
// Login
export const loginUser = userData => dispatch => {
axios
.post("/api/users/login", userData)
.then(res => {
//Save to localStorage
const { token } = res.data;
//Set token to localStorage
localStorage.setItem("jwtToken", token);
// Set token to Auth Header
setAuthToken(token);
// Decode token
const decoded = jwt_decode(token);
// Set current user
dispatch(setCurrentUser(decoded));
})
.catch(err => {
dispatch({
type: GET_ERRORS,
payload: err.response.data
});
});
};
//Set logged in user
export const setCurrentUser = decoded => {
return {
type: SET_CURRENT_USER,
payload: decoded
};
};
Run Code Online (Sandbox Code Playgroud)
减速器:
const initialState = {
isAuthenticated: false,
user: {},
loading: false
};
export default function(state = initialState, action) {
switch (action.type) {
case USER_LOADING:
return {
...state,
loading: true
};
case SET_CURRENT_USER:
return {
...state,
isAuthenticated: !isEmpty(action.payload),
user: action.payload
};
default:
return state;
}
}
Run Code Online (Sandbox Code Playgroud)
基本上,在 JWT 令牌的有效载荷中,有一些对前端代码有用的信息,例如电子邮件、用户名、头像……
但是因为 JWT 令牌只能被验证并且只能在服务器上发布(它只能在前端解码,因为前端不知道 JWT 秘密),所以每当你需要 JWT 负载中的新信息时,你需要发布新的服务器上的令牌。
适用于您的情况,您需要在更新头像后发出新的 JWT 令牌,并在 updateAvatar API 的响应中发回 JWT 令牌。
之后,您可以使用新的 JWT 令牌更新 localStorage 并在前端获取您的新头像。
| 归档时间: |
|
| 查看次数: |
2293 次 |
| 最近记录: |