如何将 JWT 从登录路由发送到即将到来的请求

问题描述 投票:0回答:1

你好,我从 Flask 服务器发送了一个 JWT http only cookie 到我的快递。当我用 JWT 身份验证向邮递员发出请求时,它可以工作,所以我认为我的后端开发没有问题。我的

/login
端点是这样的:

router.post('/login', (req, res, next) => {
 axios.post(`...../login`, {
  email: req.body.email, 
  password: req.body.password
 }, { headers: {
 ........
const token = access_token_cookie.substring(jwt_start, jwt_end);
res.locals.token = token;
next()
return res.json({
  success: response.data.success,
   .......
})
  }).catch( (err)  => {return res.status(400).json({
    success: false,
   message: 'Could not process the form.'
})})
},addAuthTokenToHeaderMiddleware);

module.exports = router;

我的

addAuthTokenToHeaderMiddleware
是一个我想“保存”我的JWT的函数

const addAuthTokenToHeaderMiddleware = (req, res, next) => {
  if (res.locals && res.locals.token) {
    req.headers['Authorization'] = `Bearer ${res.locals.token}`;
  }
  console.log('req.headers :', req.headers['Authorization'])
  next();
};

module.exports = addAuthTokenToHeaderMiddleware;

当我

console.log
时,我可以看到我的 JWT。现在我想把它发送给我的另一个即将到来的
requests
。我正在使用类似的中间件

router.route('/Organizations').post(addAuthTokenToHeaderMiddleware,asyncMiddleware(allControllers.Organizations))

我观察到,当我这样做时,

console.log
内的
addAuthTokenToHeaderMiddleware
变得不确定。所以我想在我的端点内使用这个函数中的 JWT
addAuthTokenToHeaderMiddleware

exports.Organizations = async (req, res, next) => {.....}
    
express jwt authorization
1个回答
0
投票
为什么不将令牌存储在本地存储中

const token = access_token_cookie.substring(jwt_start, jwt_end) localStorage.setItem("userInfo", JSON.stringify({ accesstoken: token }))
然后每当你想发出请求时,将其添加到你的配置对象中

const token = JSON.parse(localStorage.getItem("accesstoken")) const config = { headers: { "Content-Type": "application/json", Authorization: token, }, } const response = await axios.post( `${URL}`, data, config )
然后像这样在 addAuthTokenToHeaderMiddleware 中间件中访问它?

const addAuthTokenToHeaderMiddleware = (req, res, next) => { const token = req.header('Authorization') console.log('token', token) //... //... }

更新

如果您不想使用本地存储,另一个选择是上下文

auth-context.js

import {createContext} from "react" export const AuthContext = createContext({ isLoggedIn: false, token: null, login: () => { }, logout: () => { } })
登录操作完成后,将此行放在你的 React 应用程序中

const loginHandler = (event) => { //... const response = await fetch(url, {method, body, headers}) const data = await response.json() auth.login(data.token) // this line //.. }
然后每当你想提出请求时就这样使用它

import {useContext} from "React" import {AuthContext} from "../../shared/context/auth-context" const Component = (props) => { const auth = useContext(AuthContext) const someHandler = () = > { const config = { headers: { "Content-Type": "application/json", Authorization: 'Bearer ' + auth.token }, } const response = await axios.post( `${URL}`, data, config ) } }
不要忘记从后端返回令牌

return res.json({ success: response.data.success, token: token, //....... })
    
© www.soinside.com 2019 - 2024. All rights reserved.