Как зашифровать полезную нагрузку запроса в Reactjs - PullRequest
1 голос
/ 23 января 2020

Я работаю с реагировать js, с дополнительным шифрованием js в качестве шифрования, я пытаюсь зашифровать при запросе полезной нагрузки данных ..

Я сделал метод, такой как добавление passReqToCallback в мой паспорт но он все еще не получает результаты в запросе консоли

Я добавил результаты в шифрование как объект {data: result}, но он остается нечитаемым, поскольку запрос полезной нагрузки вместо этого считывается как форма данных

но результаты всегда 400 неверных запросов. как лучше всего это сделать?

мой reactjs код

const handleSubmit = e => {
        e.preventDefault();
        form.validateFields((err, values) => {
            if (!err) {
                const postData = {data: encrypt(values)}
                setSubmit(true);
                // eslint-disable-next-line no-undef
                axios.post(`${API}/signin`, postData)
                .then(response => {
                    return console.log('response', response.data);

                    const data = decrypt(response.data);
                    setSubmit(false)
                    if ( _.isString(data) ) {
                        contentNotification({
                            type     : 'error',
                            title    : 'Error',
                            placement: 'topLeft',
                            content  : data
                        })
                    } else {
                        contentNotification({
                            type     : 'success',
                            title    : 'Success',
                            placement: 'topLeft',
                            content  : formatMessage({id: 'LOGIN.SUCCESS'})
                        });

                        cookies.set('ckmsbp', response.data);
                        router.push('/');
                    }
                })
                .catch(err => {
                    contentNotification({
                        type     : 'error',
                        title    : 'Error',
                        placement: 'topLeft',
                        content  : formatMessage({id: 'LOGIN.ERROR_VALIDATE'})
                    })
                    setSubmit(false)
                    console.error(err);
                });
            }
        });
    };

вот мои маршруты:

app.post(`${api_path}/signin`, 
            validateBody(schemas.loginAccSchema),
            requireSignIn,
        (req, res, next) => {

            const { user }    = req
            const { decrypt } = req.query
                  params      = { user, decrypt };

            const c_account   = new ControllerAccount(params);
            c_account._postSignin(doc => res.status(200).json(doc))
    });

и последний мой паспорт

passport.use(new LocalStrategy({
    usernameField    : 'email',
passReqToCallback : true
  }, async (req, email, password, done) => {
    // return console.log('req', req);

but do nothing here.. i can't console my request

    try{
...
}
catch{...} 

заранее спасибо

Ответы [ 2 ]

0 голосов
/ 24 января 2020

после того, как я узнаю себя и, наконец, я найду то, что хочу.

лучший способ зашифровать данные в полезной нагрузке состоит в том, чтобы сделать их зашифрованными в объект, а затем, когда данные получены на контроллере, они дешифруются снова

, а затем наиболее важный способ, когда локальный Стратегия в паспорте требует только электронную почту и пароль .. поэтому снова манипулируем в req.body

в реакции js

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

после этого в контроллере nodejs

app.post(`${api_path}/signin`, 
            validateBody(schemas.loginEncryptAccSchema),
            requireSignIn, //focus in this function
        (req, res, next) => {
            const { user }    = req;
            const { decrypt } = req.query
                  params      = { user, decrypt };
            return console.log('params', params); // i stopped

            const c_account   = new ControllerAccount(params);
            c_account._postSignin(doc => res.status(200).json(doc))
    });

функция requireSignin

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

finaaaalyyy xD

0 голосов
/ 23 января 2020

Что вы можете сделать, это

Instead of doing encription and then decription in your frontend side.
You can handle it by your backend 

Simple and secure way is like you just need to pass username and password from 
your front end.

Then check both vaule are not empty.if you get any field empty then return 
error 402 with error message 

If you get both value then first check your user exist or not if not then 
return error 

If your user exist then an then you need to create token from your server side 
and store this token with your user table/document 

When you successfully store your token in users table/model then return 
response with your success message and your token.

Finally you can use your token in frontend. 

You can store this token in localStorage or as cookie in your frontend 

Then in every request which need to be authenticated you can pass your token 
in header of that request and you can verify your token from backend.

If token is not valid then you can simple throw error message that user is not 
authenticated.

Or you can give permission for sending response as per request      

Пример:

   //your data and secrete key 
   var ciphertext = CryptoJS.AES.encrypt('my message', 'secret key 123'); in crypto js    

  then you can pass it to your servere like { data : ciphertext } as payload 

  use that secrete key(like : 'secret key 123') to decrypt your reqest data in your backend side 
...