This could be “The Academy” by Robert Sheckley. It’s not an exact match (in particular, the ending is different) but it’s close.
“The Academy” takes place in a society obsessed with “sanity” and preserving the status quo. There are “sanity meters” In most public places. In addition, you can buy home sanity meters, and the protagonist owns one. A reading of zero indicates perfect sanity. If your reading goes above seven you’re required to seek therapy. If it goes above ten, or remains over seven for longer than a probationary period, you have to either submit to psychosurgery or go to The Academy. The Academy is an “enormous gray building” which supposedly offers therapy, but nobody knows what actually takes place in it and nobody ever leaves.
The protagonist, Mr. Feerman, begins the story with a sanity reading of 8.2. The bulk of the story is Feerman trying to avoid going to The Academy as his reading steadily rises. Meanwhile, it becomes clear to the reader that any dissent or even dissatisfaction is taken as a sign of potential insanity. At the end of the story, his reading goes above ten and he is taken to The Academy. He is afraid he’ll be killed, but instead a doctor gives him an injection which traps his mind permanently in a delusional fantasy.
The doctor doesn’t tell him that he is sane and the rest of the world is mad. Instead, he realizes himself that there’s nothing wrong with him and that in the long run society needs people willing to challenge the status quo. He tries to fight the effects of the injection, but fails.
You wrote: “what you were allowed in society (food, apartment...) depended on whether you were "sane" or not.”
This isn’t strictly true, but similar events take place. After Freeman’s reading goes above eight, he is let go from his job. Once it hits nine, the counterman at a diner kicks him out, saying “The law says I don’t have to serve no plus-nines.” And once it passes ten, his robot servant leaves him and his landlady says he has to leave immediately.
“The Academy” appears in Pilgrimage to Earth, and can also be read here.