Basically так и надо means "this is the way it should be". So when somebody says that something negative happened to them and you reply "
this is the way it should be'' I think it's easy to see why does it mean "it serves you right"
But you can expand on the meaning of these words by adding a verb after them. For example:
Так и надо жить - this is the way one should live

Так и надо говорить - this is the way one should speak