Civil Disobedience
Thoreau writes of how in some cases practicing civil disobedience is necessary if a law or institution is unlawful or unfair. In regards to when it is necessary, I can think that it would only be necessary if a law or institution was especially unfair to one or more groups of people, or was unlawful in nature.
One example of where it was completely justified would be in the Warsaw Uprising of 1944, where thousands of Warsaw citizens and the Polish First army rebelled against the Germans and fought them to a standstill until the Rebels eventually relented. The poles, led by Zygmunt Berling disobeyed and rebelled against what they saw as a tyrannical and unlawful occupation by the German forces.
Fighting for several months, the Uprising was eventually ended when German Reinforcements, including the infamous SS-Sturmbrigade Dirlwanger, Led by Oskar Dirlwanger, arrived and led numerous massacres against the populace, eventually burning a large portion of the city.
This is an example of justified civil disobedience. Seeing something that was subjugating the populace, and disadvantaging millions, they Polish Forces chose not to obey such illegal laws and instead chose to disobey and rebel.