Salvation is being delivered from the righteous judgment of God that will fall upon those who have sinned by breaking his law. In order to be saved from that judgment we must trust Christ. We must receive what he has done on the cross on our behalf as a substitute for us, who removes our sin (
Heb. 9:26;
2 Pet. 2:24) and gives us righteousness (
Phil. 3:9). This can only be done by faith because our righteous deeds are filthy rags before God (
Isaiah 64:6).
There are different groups that teach that salvation is attained by doing good works and trusting in Christ, such as Mormonism, Jehovah's Witnesses, etc. But this cannot be so. Sure, we want people to do good works, but it is not the good works that contribute to
salvation. Let's take a look at two sections of Scripture where Jesus teaches on this topic,
Matt. 7:22-23 and
Luke 18:9-14.
This one you quoted..
Matt. 7:22-23, "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?" 23 And then I will declare to them, "I never knew you; depart from Me, you who practice lawlessness."
You can see that on the day of judgment there will be people who believe in God and will appeal for their salvation based on their faith in him (they call him Lord) and their good deeds, i.e., prophesying, casting out demons, and performing miracles. Yet Jesus condemns them. Why? It is because they are appealing to their faith
and works.
Luke 18:9:14, "And He also told this parable to certain ones who trusted in themselves that they were righteous, and viewed others with contempt: 10 “Two men went up into the temple to pray, one a Pharisee, and the other a tax-gatherer. 11 The Pharisee stood and was praying thus to himself, ‘God, I thank Thee that I am not like other people: swindlers, unjust, adulterers, or even like this tax-gatherer. 12 ‘I fast twice a week; I pay tithes of all that I get.’ 13 But the tax-gatherer, standing some distance away, was even unwilling to lift up his eyes to heaven, but was beating his breast, saying, ‘God, be merciful to me, the sinner!’ 14 I tell you, this man went down to his house justified rather than the other; for everyone who exalts himself shall be humbled, but he who humbles himself shall be exalted.
In these verses Jesus talks about a Pharisee who believed in God, did good things, and did not do bad things. Yet, he was not saved. On the other hand, the tax gatherer (verse 13) did not appeal to works, but only asked for God's mercy. Jesus says that he was justified, not the Pharisee. That means he was legally righteous in God's eyes. Notice, Jesus taught justification by faith alone.