As we all know that the technology is projected to be next to humans very soon because of its holistic growth. Now-a-days, we see a lot of applications that are making our lives comfortable such as smart cars, smart homes, smart traffic management, smart offices, smart medical consultation, smart cities, etc. All such facilities are in the reach of a common man because of the advancement in Information and Communications Technology (ICT). Because of this advancement, new computing and communication environment such as Internet of Things (IoT) came into picture. Lot of research work is in progress in IoT domain which helps for the overall development of the society and makes the lives easy and comfortable. But in the resource constrained environment of Wireless Sensor Network (WSN) and IoT, it is almost inconceivable to establish a fully secure system. As we are moving forward very fast, technology is becoming more and more vulnerable to the security threats. In future, the number of Internet connected people will be less than the smart objects so we need to prepare a robust system for keeping the above mentioned environments safe and standardized it for the smooth conduction of communication among IoT objects. In this survey paper, we provide the details of threat model applicable for the security of WSN and IoT based communications. We also discuss the security requirements and various attacks possible in WSN and IoT based communication environments. The emerging projects of WSNs integrated to IoT are also briefed. We then provide the details of different architectures of WSN and IoT based communication environments. Next, we discuss the current issues and challenges related to WSN and IoT. We also provide a critical literature survey of recent intrusion detection protocols for IoT and WSN environments along with their comparative analysis. A taxonomy of security and privacy-preservation protocols in WSN and IoT is also highlighted. Finally, we discuss some research challenges which need to be addressed in the coming future. INDEX TERMS Wireless sensor network (WSN), Internet of Things (IoT), intrusion detection, cloud computing, fog computing, edge computing, security.