"Many will say to Me on that day, 'Lord, Lord, did we not prophesy in Your name, and in Your name cast out demons, and in Your name perform many miracles? "And then I will declare to them, 'I never knew you; DEPART FROM ME, YOU WHO PRACTICE LAWLESSNESS.'
Matthew 7:21 - Not everyone who says to Me, 'Lord, Lord,' will enter the kingdom of heaven, but he who does the will of My Father who is in heaven will enter.
John 6:40 - For my Father’s will is that everyone who looks to the Son and believes in Him shall have eternal life, and I will raise them up at the last day.
These many people (unbelievers) in Matthew 7:22 had the wrong foundation. They were trusting in their works to save them and NOT IN CHRIST ALONE. Jesus NEVER knew them which means they were NEVER saved. Their hearts were not right with God, so their attempted external obedience was stained with sin. *Seeking salvation by works is not the will of the Father.
John 17:3 - And this is eternal life, that they may know You, the only true God, and Jesus Christ whom You have sent. The term "know" implies intimate, experiential knowledge, through a relationship with Him, not merely theoretical knowledge. These many people were not true converts.
Without faith it's impossible to please God no matter how many alleged wonderful works that these many people set out to conjure up through the flesh in a vain effort to receive salvation based on their works. They were self righteous. There are false prophets who prophecy in the name of Jesus and even make false prophecies. Also, Satan may grant the power to one of his agents to cast out demons from another of his agents in order to gain attention and loyalty from an audience for his own evil agenda.
In Matthew 10:1, we also see that Jesus gave His 12 disciples power over unclean spirits, to cast them out, and to heal all kinds of sickness and all kinds of disease. This would include Judas Iscariot, yet Jesus referred to Judas Iscariot as an unbelieving, unclean devil who would betray Him! (John 6:71; 13:10-11). Apparently, Judas believed that Jesus' name has the power to cast out demons but did not truly believe in His name (John 1:12) and become a child of God, but instead was the son of perdition (John 17:12).