Though Kashmir was ruled by Mughals, it was under Sikhs rule from 19th century. Gulab Singh was Maharaj of Kashmir from 1820. He was friendly with Brithish & handed over Lahore to them and got the full state of J&K from British in an agreement. After his death in 1857, Ranbir Singh became the king. His grandson Hari Singh ascended the throne in 1925. Remember till not J&K was an independent state - neither to Pak nor to India. At that time, J&K was 77% muslims & 20% Hindus. Their legislative assembly represented their will to accede to State of Pakistan. Hari Singh had a "standstill" agreement with Pak only for trade, travel, communication etc. BUT NOT FOR ACCESSION. But, there was no similar agreement bet J&K and India...(Again remember at that point J&K was an independent state - nither part of India or Pak)..Hari Singh never wanted J&K to be a part of Pakistan. After Indian Independance Mountbatten was Gov General for sometime & Hari Singh had good relationship with British. During Oct 1947 a pakistani group called Pashtuns invaded Kashmir to frighten Hari Singh & accede Kashmir with Pak. But, Hari Singh took the help of Mountbatten & India. He signed an AGREEMENT OF ACCESSION i.e. all part of J&K belongs to India and only to India. Indian army went to J&K and drove away Pashtuns Pakistani group.
But, Pakistan objected that the ACCESSION AGREEMENT WAS FAKE. Then it was presented by India in UN & it was proved the legality of ACCESSION beyond doubt.