Wireless Sensor Networks (WSNs) are a vital component of the Internet of Things (IoT) since it is a viable technology for a variety of real-time applications. This is mainly because WSNs are naturally distributed, low-cost, fault-tolerant, self-organizing, easily deployable, scalable, and function without a predefined infrastructure. Their applications include surveillance, smart power grids, traffic networks, telecommunications systems, smart cities, intelligent transportation, industrial quality control, and the military, to mention a few. However, the security of WSNs is a major concern due to their vulnerability to various types of attacks, including node compromise, eavesdropping, and denial-of-service. This paper covers the security issues in WSNs and discusses the security challenges faced by these networks and the existing solutions. It illustrates the possible attacks and explores the different security mechanisms that can be used to protect WSNs, including encryption, authentication, and key management. Trust and reputation management are presented being effective techniques for mitigating routing attacks, and the role of machine learning techniques in enhancing WSN security is outlined. The paper concludes by discussing future research directions in WSN security. The findings of this paper are valuable for researchers, network administrators, and policymakers who are involved in the design and implementation of secure WSNs.