我正在使用react js,使用额外的cryptojs作为加密,我尝试在请求数据有效负载时进行加密..
我已经做了诸如在护照中添加 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{...}
提前致谢
在我发现自己并最终找到我想要的东西之后。
对有效负载上的数据进行加密的最佳方法是将其加密为一个对象,然后当控制器接收到数据时,它会再次解密
然后是当护照中的本地策略只需要电子邮件和密码时最重要的方法..因此在 req.body 中再次被操纵
在 React 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))
});
需要登录功能
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);
}
finaaaalyyyxD
您可以使用 JWT 加密并创建当快递处理请求时后端可以理解/解码的算法。
const jwtDetails = {
secret: 'your secret',
key: 'your key'
};
jwtEncrypt.generateJWT(
jwtDetails,
payload,
constants.encryption,
).then(token => {
// use your token on you request payload
});
在您的请求负载上,它将如下所示。
data: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJmZDJhMDA0Yy0wMTIzLTRmZDctOGEzMi1mY2MzZGJiMmQ1YjAiLCJkYXRhIjp7InB1YmxpYyI6eyJhY2NvdW50IjoiNDAwNyIsInBhc3N3b3JkIjoiMTIzNDU2IiwiYXBpX2tleSI6IkREZTgwZjg0MWVhN2JjOWU3ODk0NmUwYjlkNmQ5YjdlMjAwZWQ1NDY4YSIsInVzZXJfdHlwZSI6WyJBR0VOVCJdfSwiZW5jRGF0YSI6ImQxYmJhNjJhMzE2NWI2MDRhYTM2YTU3ZGZjNTQ2ZTRmIn0sImlhdCI6MTYxNTczMDQ4NCwiZXhwIjoxNjE1NzczNjg0fQ.xVbWKBYJBvpHeYVMqr96nYkLNqkoiOeWRkZ5GmiOi3w
你能做的是
Instead of doing encryption and then decryption 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 value 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