In wireless sensor networks (WSNs), protocols with authentication and key agreement functions can enhance the security of the interaction between users and sensor nodes, guaranteeing the security of user access and sensor node information. Existing schemes have various security vulnerabilities and are susceptible to security attacks (e.g., masquerading user, password guessing, internal privilege, and MITT attacks), so they cannot meet the anonymity requirements or achieve forward security. To effectively improve the security performance of WSNs, an elliptic curve cryptography (ECC)-based three-factor authentication and key agreement scheme for WSNs is proposed. The scheme is based on the ECC protocol and combines biometrics, smart card and password authentication technology; uses a challenge/response mechanism to complete the authentication between users, gateways, and sensors; and negotiates a secure session key. The Burrows, Abadi and Needham logic for formal security analysis proves the correctness and security of the scheme, and the informal analysis of multiple known attacks proves that the scheme can resist various attacks and has high security characteristics. The feasibility of the scheme has been analysed and verified with the ProVerif tool. The efficiency analysis results show that the scheme is suitable for resource-constrained WSNs.