axios 如何在Reactjs中加密请求负载

zbdgwd5y  于 2024-01-07  发布在  iOS
关注(0)|答案(3)|浏览(94)

我正在使用react js,使用额外的cryptojs作为加密,我尝试在请求数据有效载荷时加密。
我已经做了一个方法,如添加passReqToCallback到我的护照,但它仍然没有得到结果,在控制台请求
我已经将结果作为对象{data:result}添加到加密中,但它仍然不可读,因为有效负载请求读取为数据表单
但结果总是400个错误的请求。最好的方法是什么?
reactjs代码

  1. const handleSubmit = e => {
  2. e.preventDefault();
  3. form.validateFields((err, values) => {
  4. if (!err) {
  5. const postData = {data: encrypt(values)}
  6. setSubmit(true);
  7. // eslint-disable-next-line no-undef
  8. axios.post(`${API}/signin`, postData)
  9. .then(response => {
  10. return console.log('response', response.data);
  11. const data = decrypt(response.data);
  12. setSubmit(false)
  13. if ( _.isString(data) ) {
  14. contentNotification({
  15. type : 'error',
  16. title : 'Error',
  17. placement: 'topLeft',
  18. content : data
  19. })
  20. } else {
  21. contentNotification({
  22. type : 'success',
  23. title : 'Success',
  24. placement: 'topLeft',
  25. content : formatMessage({id: 'LOGIN.SUCCESS'})
  26. });
  27. cookies.set('ckmsbp', response.data);
  28. router.push('/');
  29. }
  30. })
  31. .catch(err => {
  32. contentNotification({
  33. type : 'error',
  34. title : 'Error',
  35. placement: 'topLeft',
  36. content : formatMessage({id: 'LOGIN.ERROR_VALIDATE'})
  37. })
  38. setSubmit(false)
  39. console.error(err);
  40. });
  41. }
  42. });
  43. };

字符串
以下是我的路线:

  1. app.post(`${api_path}/signin`,
  2. validateBody(schemas.loginAccSchema),
  3. requireSignIn,
  4. (req, res, next) => {
  5. const { user } = req
  6. const { decrypt } = req.query
  7. params = { user, decrypt };
  8. const c_account = new ControllerAccount(params);
  9. c_account._postSignin(doc => res.status(200).json(doc))
  10. });


最后我的护照

  1. passport.use(new LocalStrategy({
  2. usernameField : 'email',
  3. passReqToCallback : true
  4. }, async (req, email, password, done) => {
  5. // return console.log('req', req);
  6. but do nothing here.. i can't console my request
  7. try{
  8. ...
  9. }
  10. catch{...}


thanks in advance

iqjalb3h

iqjalb3h1#

在我找到我自己并最终找到我想要的之后
对有效载荷上的数据进行加密的最佳方式是将其加密到对象中,然后当控制器上接收到数据时,再次对其进行解密
然后最重要的方式,当本地策略在护照只想要电子邮件和密码只..所以操纵再次在请求.身体
在React JS中

  1. const result = {data : encrypt(values)}
  2. axios.post(`${API}/signin`, result) // I simplify the coding

字符串
在控制器nodejs中,

  1. app.post(`${api_path}/signin`,
  2. validateBody(schemas.loginEncryptAccSchema),
  3. requireSignIn, //focus in this function
  4. (req, res, next) => {
  5. const { user } = req;
  6. const { decrypt } = req.query
  7. params = { user, decrypt };
  8. return console.log('params', params); // i stopped
  9. const c_account = new ControllerAccount(params);
  10. c_account._postSignin(doc => res.status(200).json(doc))
  11. });


requireSignin函数

  1. const requireSignIn = (req, res, next) => {
  2. const data = req.body.data;
  3. const bytes = CryptoJS.AES.decrypt(data, `${KEY_CHAIN}`); //i decrypt
  4. req.body = JSON.parse(bytes.toString(CryptoJS.enc.Utf8)); //then i assign into req.body again
  5. passport.authenticate('local', { session : false })(req, res, next);
  6. }


finaaaalyyy xD

展开查看全部
xv8emn3q

xv8emn3q2#

您可以使用JWT加密并创建后端可以在express处理请求时理解/解码的算法。

  1. const jwtDetails = {
  2. secret: 'your secret',
  3. key: 'your key'
  4. };
  5. jwtEncrypt.generateJWT(
  6. jwtDetails,
  7. payload,
  8. constants.encryption,
  9. ).then(token => {
  10. // use your token on you request payload
  11. });

字符串
在你的请求有效载荷上,它看起来像这样。

  1. data: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJmZDJhMDA0Yy0wMTIzLTRmZDctOGEzMi1mY2MzZGJiMmQ1YjAiLCJkYXRhIjp7InB1YmxpYyI6eyJhY2NvdW50IjoiNDAwNyIsInBhc3N3b3JkIjoiMTIzNDU2IiwiYXBpX2tleSI6IkREZTgwZjg0MWVhN2JjOWU3ODk0NmUwYjlkNmQ5YjdlMjAwZWQ1NDY4YSIsInVzZXJfdHlwZSI6WyJBR0VOVCJdfSwiZW5jRGF0YSI6ImQxYmJhNjJhMzE2NWI2MDRhYTM2YTU3ZGZjNTQ2ZTRmIn0sImlhdCI6MTYxNTczMDQ4NCwiZXhwIjoxNjE1NzczNjg0fQ.xVbWKBYJBvpHeYVMqr96nYkLNqkoiOeWRkZ5GmiOi3w

展开查看全部
ukdjmx9f

ukdjmx9f3#

你能做的就是

  1. Instead of doing encryption and then decryption in your frontend side.
  2. You can handle it by your backend
  3. Simple and secure way is like you just need to pass username and password from
  4. your front end.
  5. Then check both value are not empty.if you get any field empty then return
  6. error 402 with error message
  7. If you get both value then first check your user exist or not if not then
  8. return error
  9. If your user exist then an then you need to create token from your server side
  10. and store this token with your user table/document
  11. When you successfully store your token in users table/model then return
  12. response with your success message and your token.
  13. Finally you can use your token in frontend.
  14. You can store this token in localStorage or as cookie in your frontend
  15. Then in every request which need to be authenticated you can pass your token
  16. in header of that request and you can verify your token from backend.
  17. If token is not valid then you can simple throw error message that user is not
  18. authenticated.
  19. Or you can give permission for sending response as per request

字符串
范例:

  1. //your data and secrete key
  2. var ciphertext = CryptoJS.AES.encrypt('my message', 'secret key 123'); in crypto js
  3. then you can pass it to your servere like { data : ciphertext } as payload
  4. use that secrete key(like : 'secret key 123') to decrypt your reqest data in your backend side

展开查看全部

相关问题