I have a frontend Angular.ts and a backend Express.js. I am decrypting user credentials in the frontend using RSA and sending all the data as an encrypted string to the backend.
When I try to catch the data in the backend to decrypt it, it reads the received object as [object Object] which makes it impossible to decrypt. This is the code =>:
FRONTEND httpService.ts:
sendmail(user: { name: any; email: any; host: any }) {
console.log(user);
const encJsonUser = this.rsaHelper.encryptWithPublicKey(
JSON.stringify(user)
);
console.log(encJsonUser);
return this.http.post(environment.apiUrl + '/sendemail', encJsonUser);
}
BACKENDemail.js:
router.post('/', async (req, res) => {
let path = null;
const encryptedData = req.body;
console.log("RECEIVED ENCRYPTED BODY: " + encryptedData);
const privateKey = fs.readFileSync("privateKey.key.pem", "utf8");
console.log("toDecryptData::: " + encryptedData);
const decryptedData = decryptedDataFromAngular(encryptedData, privateKey);
console.log("DECRYPTED-DATA: " + decryptedData);
axios.post("http://localhost:8080/pdf", {host: encryptedData.host}).then(async function (response) {
path = response.data.scan_id;
}).then(() => {
emailPdfGenerator(encryptedData);
});
})
function decryptedDataFromAngular(encryptedData, privateKey) {
// encryptedData = Buffer.from(encryptedData, "base64");
const body = JSON.parse(encryptedData);
// console.log("ENCRYPTED DATA 2222:::: " + encryptedData);
console.log("ENCRYPTED DATA 2222:::: " + body);
const decryptedData = crypto.privateDecrypt(
{
key: privateKey,
// In order to decrypt the data, we need to specify the
// same hashing function and padding scheme that we used to
// encrypt the data in the previous step
padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,
oaepHash: "sha256",
},
body
);
console.log("decrypted data: ", decryptedData.toString());
console.log("DE RAW DATA" + decryptedData);
return decryptedData;
}
error message:
RECEIVED ENCRYPTED BODY: [object Object] toDecryptData::: [object Object] undefined:1 [object Object] ^
SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse ()
at decryptedDataFromAngular (C:\Users\hayan\Desktop\HSLeiden\Year2-IN2B\IPSEN5\Security-Check-Express-User\routes\email.js:60:23)
at C:\Users\hayan\Desktop\HSLeiden\Year2-IN2B\IPSEN5\Security-Check-Express-User\routes\email.js:31:27
at Layer.handle [as handle_request] (C:\Users\hayan\Desktop\HSLeiden\Year2-IN2B\IPSEN5\Security-Check-Express-User\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\hayan\Desktop\HSLeiden\Year2-IN2B\IPSEN5\Security-Check-Express-User\node_modules\express\lib\router\route.js:144:13)
at Route.dispatch (C:\Users\hayan\Desktop\HSLeiden\Year2-IN2B\IPSEN5\Security-Check-Express-User\node_modules\express\lib\router\route.js:114:3)
at Layer.handle [as handle_request] (C:\Users\hayan\Desktop\HSLeiden\Year2-IN2B\IPSEN5\Security-Check-Express-User\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\hayan\Desktop\HSLeiden\Year2-IN2B\IPSEN5\Security-Check-Express-User\node_modules\express\lib\router\index.js:284:15
at Function.process_params (C:\Users\hayan\Desktop\HSLeiden\Year2-IN2B\IPSEN5\Security-Check-Express-User\node_modules\express\lib\router\index.js:346:12)
at next (C:\Users\hayan\Desktop\HSLeiden\Year2-IN2B\IPSEN5\Security-Check-Express-User\node_modules\express\lib\router\index.js:280:10)
[nodemon] app crashed - waiting for file changes before starting...
I stopped using crypto, and I am using forge to solve the problem because crypto just didn't help me.
This is my code:
async function decryptUser(encryptedUserData) {
const name = await decryptString(encryptedUserData.name);
const email = await decryptString(encryptedUserData.email);
const host = await decryptString(encryptedUserData.host);
const decryptedUser = {
name: name,
email: email,
host: host,
}
return decryptedUser
}
async function decryptString(encryptedString) {
const rsa = forge.pki.privateKeyFromPem(PRIVATE_KEY);
return await rsa.decrypt(encryptedString);
}
Related
here I generate the token at backend in express
..............
router.post("/login",async(req,res)=>{
const {email,password}=req.body;
if(!email || !password){
return res.status(401).send({error:"please filled the data properly"});
}
try {
const loginUser=await User.findOne({email:email});
if(!loginUser){
return res.status(400).send({error:"not found"});
}
const isMatch = await bcrypt.compare(password,loginUser.password);
if(isMatch){
const token=await loginUser.generateToken();
res.cookie("jwtoken",token,{
expires:new Date(Date.now()+15000000),
httpOnly:true,
//secure:true //it is applicable when we use https method
})
console.log(token);
res.send({message:"login success"});
}else{
res.status(400).send({error:"please enter correct data"})
}
} catch (error) {
res.status(400).send(error)
}
})
the token is create when i login in brouser
here is the about page (react)
...................
const verifyPage=async()=>{
try{
const res=await fetch('/about',{
method:"GET",
headers:{
Accept:"application/json",
"Content-Type":"application/json"
},
credentials:"include"
});
const data=await res.json();
console.log(data);
if(!res.status===200){
const err=new Error(res.error);
throw err;
}
}catch(err) {
console.log(err);
history.push("/login");
}
}
useEffect(()=>{
verifyPage();
},[])
.............
here I verify the token
...........
router.get("/about",Authentication,(req,res)=>{
res.send(req.rootUser);
})
........
The authentication page
............
const jwt = require("jsonwebtoken")
const User=require("../models/shegma")
const Authentication=async (req,res,next)=>{
try{
const token=req.cookies.jwtoken;
console.log(token)
const verifyToken=jwt.verify(token,process.env.TOKENID);
console.log(verifyToken);
const rootUser=await User.findOne({_id:verifyToken._id,"tokens.token":token})
if(!rootUser){throw new Error("user not found")}
req.token=token;
req.rootUser=rootUser;
req.userID=rootUser._id;
next();
}catch(err){
res.status(401).send("no token found");
console.log(err);
}
}
module.exports=Authentication;
..........
here is the error
......
TypeError: Cannot read property 'jwtoken' of undefined
at Authentication (C:\Users\ASUS\Desktop\mern\server\middleware\Authentication.js:6:33)
at Layer.handle [as handle_request] (C:\Users\ASUS\Desktop\mern\server\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\ASUS\Desktop\mern\server\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (C:\Users\ASUS\Desktop\mern\server\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\Users\ASUS\Desktop\mern\server\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\ASUS\Desktop\mern\server\node_modules\express\lib\router\index.js:281:22
at Function.process_params (C:\Users\ASUS\Desktop\mern\server\node_modules\express\lib\router\index.js:335:12)
at next (C:\Users\ASUS\Desktop\mern\server\node_modules\express\lib\router\index.js:275:10)
at Function.handle (C:\Users\ASUS\Desktop\mern\server\node_modules\express\lib\router\index.js:174:3)
at router (C:\Users\ASUS\Desktop\mern\server\node_modules\express\lib\router\index.js:47:12)
At first, you need to install cookie-parser inside your server folder
npm i cookie-parser
Then, require cookie-parser inisde that .js file where you have initialized express
const cookieParser = require('cookie-parser')
After this, below const app = express(); just write
app.use(cookieParser())
Here is the full code:-
const express = require('express');
const cookieParser = require('cookie-parser')
const app = express();
app.use(cookieParser())
Do you happen to be parsing the cookies on the incoming request anywhere in your express code?
The req.cookies object being undefined leads me to believe you may not be parsing the request for cookies or that the parsing is not happening before the Authentication handler is called.
For reference: express cookie-parser
I'm sending the below request from an angular app to my node backend. However, I cant seem to access the body of the request, instead just getting undefined being printed by the console. Where am I going wrong?
Request
Angular post request
logIn(email: string, password: string) {
return this.http.post('http://localhost:8080/login', { email: email, password: password });
}
NodeJS backend
var http = require('http');
http.createServer(function (req, res) {
let chunks = [];
req.on('data', chunk => chunks.push(chunk));
req.on('end', () => {
let data = Buffer.concat(chunks);
let schema = JSON.parse(JSON.stringify(data));
console.log('Data: ', schema.email);
});
}).listen(8080);
I am trying to implement the ability of the server to generate and validate JWT. I didn't have experience in TypeScript and Postman before so I got this error from the server:
json: Unexpected string in JSON at position 26
This is the request I am sending with Postman
This is the function I use to generate JWT:
app.post("/generate", async (req, res) => {
console.log("req.body: " + req.body)
let body: any = await req.body;
const { name } = await body.value;
let token = await generateUserJWT(name)
res.json({ status: true, data: name, token:token });
});
What is wrong with my request?
I am supposed to send data from an app to the server and the post method from that app is made using content type as application/json but it is plain text. I cannot update the app to change this header now. The current app is working as the data reaches PHP directly and PHP doesn't parse the incoming data which is specified as json.
import express from 'express'
var http = require('http')
const redirectionRoutes = express.Router()
redirectionRoutes.use(function(req, res, next) {
req.rawBody = ''
req.headers['content-type'] = 'text/plain'
req.on('data', function(chunk) {
req.rawBody += chunk
})
req.on('end', function() {
next()
})
})
redirectionRoutes.post(/^\/update_services\/.*$/, function(request, response) {
var data = request.rawBody
var dataLength = data.length
var options = {
hostname: 'localhost',
port: 80,
path: request.path,
method: 'POST',
json: false,
headers: {
'Content-Type': 'text/plain',
'Content-Length': dataLength
}
}
var buffer = ''
var req = http.request(options, function(res) {
res.on('data', function(chunk) {
buffer += chunk
})
res.on('end', function() {
response.send(buffer)
})
})
req.write(data)
req.end()
})
But in nodejs(my application), as the content type is specified as json, the body parser is parsing the data and as it's not json, I am getting an error:
SyntaxError: Unexpected token # in JSON at position 0
at JSON.parse (<anonymous>)
at createStrictSyntaxError (../node_modules/body-parser/lib/types/json.js:157:10)
at parse (../node_modules/body-parser/lib/types/json.js:83:15)
at /Users/../node_modules/body-parser/lib/read.js:116:18
at invokeCallback (/Users/../node_modules/body-parser/node_modules/raw-body/index.js:224:16)
at done (/Users/../node_modules/body-parser/node_modules/raw-body/index.js:213:7)
at IncomingMessage.onEnd (/Users/../node_modules/body-parser/node_modules/raw-body/index.js:273:7)
at emitNone (events.js:105:13)
at IncomingMessage.emit (events.js:207:7)
at endReadableNT (_stream_readable.js:1047:12)
Is there a way in nodejs/body parser to not to parse this incoming json and let is get into the function as plain text.
It is solved!!
I am exporting this module at the end of the app code along with other pages routers. So, the body-parser being called in previous libraries are being called if I didn't use in this particular router.
I am working on an Express App with MongoDB and trying to utilize FeathersJS for all my services. Here I'm running a test try to get an error message from the server to the client, but I have an issue with the response from the error handler. My req headers have the correct application/json stuff, so I assumed the Error Handler should send valid json back.
I know I'm not using the next callback in my function, but when I try to do that it gives the same error, so I'm thinking it has to do with the Error Handler. Any direction here would be greatly appreciated!
The first error log is on the server, which is correct.
Bucket Services
error >>>>> Bucket validation failed
Possibly Unhandled Rejection: Bucket validation failed, Promise { <rejected> 'Bucket validation failed' }
>>>>>> Error: Unexpected token < in JSON at position 0
at convert (/Users/jaruesink/Documents/Projects/Buckets/node_modules/feathers-rest/node_modules/feathers-errors/lib/index.js:365:79)
at toError (/Users/jaruesink/Documents/Projects/Buckets/node_modules/feathers-rest/lib/client/base.js:24:37)
at process._tickCallback (internal/process/next_tick.js:103:7)
my create function within the BucketService class:
create({
amount,
isFund = false,
name,
type,
userID: owner
}, params, next) {
const new_bucket = new Bucket({ name, amount, type, isFund, owner });
return new_bucket.save((error) => {
console.log('error >>>>>', error.message);
if (error) { return Promise.reject(error.message); }
return Promise.resolve(new_bucket);
});
}
my router file:
const feathers = require('feathers');
const errorHandler = require('feathers-errors/handler');
const rest = require('feathers-rest');
const router = feathers();
const LoginService = require('../services/login_service');
const UserService = require('../services/user_service');
const BucketService = require('../services/bucket_service');
// Enable REST services
router.configure(rest());
router.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
next();
});
router.use('/login', new LoginService());
router.use('/user', new UserService());
router.use('/bucket', new BucketService());
// Set up error handling
router.use(errorHandler());
module.exports = router;
I figured it out, the key was to correctly pass through a callback (next) function as the third parameter to handle errors. FeathersJS handles the Promise Rejections for you on errors. Then in my test I needed to convert the Feathers-Error to JSON before I could get the message.
I changed my test to:
it('can validate an incorrect bucket', (done) => {
const invalid_bucket = {
name: 'Invalid Bucket',
};
bucket_service.create(invalid_bucket, {}, (error) => {
error = error.toJSON();
assert(error.message.length > 0);
done();
});
});
and my create function to:
create({
amount,
isFund = false,
name,
type,
userID: owner
}, params, next) {
const new_bucket = new Bucket({ name, amount, type, isFund, owner });
return new_bucket.save()
.then(created_bucket => Promise.resolve(created_bucket))
.catch(next);
}