Denial of service (DoS) attack is an impelling inside attack in the form of interference or collision at the receiver side, which can causes serious damage to the functions of wireless sensor networks (WSNs). In this paper, we propose a solution using one-way hash function to generate dynamic keys ensuring that even if the adversaries may acquire the current or earlier keys, they have no ability to decrypt the next legitimate key. Therefore, adversaries can been prevent from injecting bogus packets or relayed packets in-cluster therefore defending against DoS attacks. Our proposed solution is lightweight, tolerates bursts of packet losses, and can easily be implemented in modern WSNs. Through security analyze and simulation, we can see that our proposed scheme can efficiently detect and defend against DoS attacks.