The futuristic fifth-generation cellular network (5G) not only supports high-speed internet, but must also connect a multitude of devices simultaneously without compromising network security. To ensure the security of the network, the Third Generation Partnership Project (3GPP) has standardized the 5G Authentication and Key Agreement (AKA) protocol for mutually authenticating user equipment (UE), base stations, and the core network. However, it has been found that 5G-AKA is vulnerable to many attacks, including linkability attacks, denial-of-service (DoS) attacks, and distributed denial-of-service (DDoS) attacks. To address these security issues and improve the robustness of the 5G network, in this paper, we introduce the Secure Blockchain-based Authentication and Key Agreement for 5G Networks (5GSBA). Using blockchain as a distributed database, our 5GSBA decentralizes authentication functions from a centralized server to all base stations. It can prevent single-point-of-failure and increase the difficulty of DDoS attacks. Moreover, to ensure the data in the blockchain cannot be used for device impersonation, our scheme employs the one-time secret hash function as the device secret key. Furthermore, our 5GSBA can protect device anonymity by mandating the encryption of device identities with Subscription Concealed Identifiers (SUCI). Linkability attacks are also prevented by deprecating the sequence number with Elliptic Curve Diffie–Hellman (ECDH). We use Burrows–Abadi–Needham (BAN) logic and the Scyther tool to formally verify our protocol. The security analysis shows that 5GSBA is superior to 5G-AKA in terms of perfect forward secrecy, device anonymity, and mutual Authentication and Key Agreement (AKA). Additionally, it effectively deters linkability attacks, replay attacks, and most importantly, DoS and DDoS attacks. Finally, the performance evaluation shows that 5GSBA is efficient for both UEs and base stations with reasonably low computational costs and energy consumption.