The nature of wireless sensor networks (WSNs) makes them very vulnerable to adversary's malicious attacks. Therefore, network security is an important issue to WSNs. Due to the constraints of WSN, intrusion detection in WSNs is a challengeable task. In this paper, we present a novel intrusion detection mechanism for WSNs, which is composed of a secure data communication algorithm and an intrusion detection algorithm. The major contribution of this paper is that we propose an original secure mechanism to defend WSNs against malicious attacks by using the information generated during data communication. The approach is able to protect the data communication in a WSN even if some sensor nodes are compromised by adversary. The proposed approach is easy to be implemented and performed in resource-constrained WSN. We also evaluate the proposed approach by a simulation experiment and analyze the simulation results in detail.