Sadiq Khan unveils posters on final day of his campaign

Yes we Khan: The inside story of how Sadiq Khan defeated a dog-whistle campaign

"This feels like 1997," an aide to Sadiq Khan says as he stands in glorious sunshine in the garden of Southwark Cathedral. Minutes earlier, London's first Muslim mayor had signed his declaration of office during a ceremony overlooked by the Bishop of Southwark and Doreen Lawrence, mother of the murdered black teenager Stephen.

"I grew up on a council estate just a few miles from here," Khan told the audience inside the cathedral.

"Back then I never dreamt that I could be standing here as the mayor of London,"

Just outside the garden, crowds of well-wishers had gathered on the edge of Borough Market to snatch a glimpse of the man himself. When he finally emerged from the cathedral, there were shouts of "congratulations" and a round of applause as Khan made his way through the crowd of friends, family and a smattering of admiring celebrities. His face and name were by now leading news items around the world.

"Congratulations to Sadiq Khan. Son of a Pakistani bus driver, champion of workers' rights and human rights, and now Mayor of London," US presidential favourite Hillary Clinton tweeted later that day.

For a man who, until a few months ago, was a little-known former transport minister, it has been an incredible transformation. And it is a transformation which comes after one of the nastiest and most bitterly fought election campaigns in living memory.

Sadiq Khan signs his declaration of office inside Southwark Cathedral

For months, Khan's opponent Zac Goldsmith led almost constant attacks against him for alleged links to Muslim 'extremists'. The allegations were repeatedly amplified through a concerted campaign by senior Conservatives and supportive newspapers.

Many in Labour feared the attacks would cause a collapse in turnout among Labour supporters. In fact, when the results finally came in, Khan had not only won, but had done so on a scale bigger than either Boris Johnson or Ken Livingstone before him. It was a result which clearly vindicated the approach taken by the Labour candidate.

The key to understanding Khan's success is to realise that both Khan and most of his senior lieutenants are former Miliband staffers. Khan, who had previously masterminded Ed's leadership bid, watched in horror last year as the Conservatives successfully defined him as weak, awkward and unfit to be prime minister. It was a brutal experience, which most of those around Khan witnessed first hand. They were all determined not to repeat the same mistakes again.

"The most important lesson from Miliband was that Sadiq needed to define himself before his opponents had a chance to," one ally of Khan told me.

Ed Miliband arrives at Southwark Cathedral after Sadiq Khan's victory

With this in mind, Khan's team sat down, worked out how the Tories were most likely to attack him and then tried to neutralise those attacks in advance. Khan's decision to nominate Jeremy Corbyn for Labour leader (to "broaden the debate") was one obvious weak spot. With this in mind, shortly after being selected, Khan gave an interview to the Mail on Sunday in which he repeatedly laid into his party's new leader.

Long before the Labour anti-semitism row broke, Khan attacked Corbyn for allowing the party to be seen as "anti-Jewish" while savaging him over his connections to Hamas and Hezbollah. Khan also attacked Corbyn for refusing to sing the national anthem and slammed Labour's shadow chancellor John McDonnell for "condoning" the IRA. It was a brutal interview which enraged many Labour activists who had voted for Khan as the 'left' alternative to Tessa Jowell. But it was also highly effective at closing off what could have been the Conservative's best line of attack against him. Months later a list would leak from within Labour HQ showing that Corbyn's team viewed Khan as "hostile" to him. The Mail on Sunday interview had done the trick.

It was an early sign of Khan's utter ruthlessness. It would not be the last.

The other key line of attack that Khan's team anticipated centred on his previous work as a human rights lawyer in which he represented, in his own words, "some unsavoury characters". Khan's team were right to anticipate this line of attack. Several commentators have suggested that Goldsmith's campaign resorted to these attacks out of desperation. This is not the case. In fact, even before Goldsmith was nominated, a source on his campaign told me that they were likely to attack Khan for his 'extremist' connections. Khan's former brother-in-law Makbool Javaid's previous status as a firebrand was also specifically mentioned to me. Sure enough, a story linking Khan to Javaid was the first 'extremist link' story to appear about Khan in the Evening Standard earlier this year.

Again, Khan was well prepared for the attack. Knowing it was coming, Khan gave a well-received lunchtime speech to the parliamentary lobby in November last year. He spoke passionately about his own experience of fighting and being subject to attacks from Islamic extremists. In a line clearly targeted to the views of certain newspapers and their readers, Khan argued that British Muslims had a "special role" in tackling Islamic extremes. Again, Khan's speech and its warm reception by 'the Tory press' won grumbles and even outrage from some on the left, but it was highly effective in neutering the attacks which were soon to come in abundance.

Key to the success of Khan's pre-emptive strategy was his chief spinner Patrick Hennessy, a former Telegraph journalist with strong links to Conservative-supporting newspapers. Whereas Goldsmith's team had pretty poor relations with any but the most supportive publications, Hennessy ensured that Khan's messages appeared in exactly the sort of newspapers which the Tories would later seek to use to attack him.

"They made sure that The Sun and Mail readers had already heard from Khan before they heard from the Tories about him," one ally of Khan tells me.

Zac Goldsmith was convinced that Sadiq Khan was a danger to London

But heading off attacks wasn't going to be enough. Khan's team knew they also had to avoid the biggest mistake made by Miliband, and positively define the Labour candidate with voters. So long before the race properly began, Khan began to wheel out his lines about being "the son of a bus driver" and "the council estate boy who will tackle the housing crisis". Khan followed these lines so religiously that journalists covering the race would often grumble that they could recite them in their sleep. This was another lesson learned from the Miliband years when the Tories endlessly and successfully repeated messages such as Osborne's "long-term economic plan" to the increasing boredom of journalists.

"We had a few simple key messages, which we devised early and keep repeating," one source tells me.

"The fact that you guys [in the media] were fed up with them we viewed as a measure of success," they added. Sure enough, by the time voters went to the polls, Khan's rags-to-riches story was firmly implanted both in journalists' and in voters' minds.

Khan's life story also served another use as an indirect criticism of Goldsmith's very different upbringing. With the exception of one poorly-judged poster attacking the Conservative candidate for being a "serial underachiever," Khan's campaign never directly attacked Goldsmith for his wealth. Instead, Khan's repeated reference to his own humble beginnings allowed voters to make their own comparison. In this way, Khan's constant reference to his bus driver father was an unsubtle but entirely deniable dog-whistle Fto those voters wary of electing a millionaire former non-dom to become mayor.

Not everything ran smoothly for Khan. Around the turn of the year, big questions emerged about the funding for Khan's proposed four year freeze for transport fares. Labour claimed the policy would cost just £450 million over four years. However, a briefing sent by Transport for London (TfL) to news organisations, including Politics.co.uk, suggested it would actually cost £1.9 billion. The row looked briefly like it might be Khan's undoing after he struggled repeatedly to square the two figures. In one tense interview with BBC London's transport correspondent Tom Edwards, he denied that TfL had even made the estimate, despite the fact that Edwards had himself received it. In a momentary lack of control, Khan raised his voice with Edwards, telling him "I'm correcting you…"

Zac Goldsmith looks on as Sadiq Khan gives his victory speech

Goldsmith's campaign were initially excited about Khan's stumble, yet their private polls suggested the row had failed to dent Khan's lead. Indeed, the Labour candidate actually appeared to be increasing his support as election day drew nearer. With an increasingly awkward-looking Goldsmith failing to impress voters, the Tory campaign, now under the direction of Lynton Crosby's colleague Mark Fullbrook, decided to double down their attacks on Khan's 'extremist' links.

These attacks had been prepared long in advance. Leaflets sent out by his campaign last year had labelled Khan as "radical" and "divisive". At the time, Goldsmith's campaign denied that this was in any way an attempt to play on fears about Khan's Muslim background. However, Khan's team weren't willing to let it go.

"We took a deliberate decision to call that out when we saw it," one source on Khan's campaign tells me.

"We needed to draw a line in the sand."

Khan's team claimed that the leaflets were a form of "coded racism" against their candidate. Yet rather than discourage Goldsmith from pursuing this line of attack, Khan's reaction actually convinced the Conservative candidate to go even further. Goldsmith's aides prepared a dossier of Khan's 'links' to extremists and sat the Tory candidate down in an attempt to convince him that the Labour candidate was a genuine danger to London.

In recent days, some commentators have suggested that Goldsmith was 'held hostage' by his own campaign on this issue. Yet those around Goldsmith say he was just as convinced, if not more convinced, of the case against Khan than they were. Far from being a hostage of the campaign, Goldsmith was an evangelist for it.

As a result, a smear campaign which was initially played out solely through third parties in the press was gradually drawn towards Goldsmith himself. At first, stories about Khan's links were briefed to supportive newspapers by Goldsmith's campaign under the condition that they were not credited as coming from them directly. Signs of this were seen in February when three or four Conservative-supporting newspapers released almost simultaneous flimsy stories about Khan's 'extremist links', none of which contained direct quotes from Goldsmith or his campaign.

Yet, as the polls showed the attacks weren't getting through, Goldsmith and other senior Conservatives began to take ownership of them. In a front page story in the Evening Standard, defence secretary Michael Fallon said that Khan was "unfit" to be put in charge of London's police force due to the fact that he had shared platforms with 'extremists'. Fallon was followed by the home secretary Theresa May, who attacked Khan for his support for terror suspect Babar Ahmad and Michael Gove who suggested that Khan may even support Sharia law.

The intent of the Tory campaign was no longer possible to deny. This was clearly a deliberate attempt to scare Londoners, one third of which had told pollsters they were worried about the prospect of a Muslim mayor, from voting for him. By the time David Cameron repeated some of the same allegations in the House of Commons, Khan's team were clearly rattled.

"When the prime minister stood up at prime minister's questions and repeated all that stuff, we were obviously worried that it would have an effect," one ally of Khan tells me.

Yet almost all the attacks quickly backfired. May's attempts to link Khan to Babar Ahmad soon fell apart after Politics.co.uk revealed that Goldsmith had himself been a supporter of his campaign against extradition to the US. When Khan pressed him on this, Goldsmith denied having even heard of Ahmad until "quite recently". Yet video and correspondence which I later unearthed, revealed that he had in fact repeatedly lobbied ministers about Ahmad's case as early as 2010.

The prime minister's attacks on Khan for 'sharing a platform' with controversial Tooting Imam Suliman Gani also quickly fell apart after it turned out that Gani was actually a Conservative supporter who had fallen out with Khan due to the Labour MP's support for equal marriage. To the Conservatives' increasing embarrassment, Gani quickly published a picture of himself and Goldsmith standing on the street together. Goldsmith's campaign initially suggested it was a random encounter, however it later emerged that it was taken outside a 'become a councillor' event hosted by the local Tooting candidate Dan Watkins which was attended by both men. Text messages and emails revealed that Watkins had personally invited Gani to the event, which was also attended by international development secretary Justine Greening.

By now it was clear that the case against Khan was falling apart. Polling suggested that few Londoners were willing to describe the Labour candidate as "extreme" or dangerous, with some even suggesting Goldsmith was more likely to be labelled in this way.

But rather than back down, the Conservative campaign gave it one last push. With just one week to go, Goldsmith published an op-ed in the Mail on Sunday warning about Khan and his 'extremist links'. The article was accompanied by a photo of the London bus blown up by terrorists in 2005 and the headline "On Thursday, are we really going to hand the world's greatest city to a Labour party that thinks terrorists are its friends?"

The article caused immediate and widespread outrage. The attempt to link Khan to the murder of ordinary Londoners had clearly gone too far.

Goldsmith's campaign quickly pointed out that they had no choice in selecting the photo or headline, but it was too late. The damage had been done. The furious reaction to Goldsmith's campaign, which had been brewing for months now, finally boiled over. Those on the left who might otherwise had been indifferent, or even hostile, to Khan's candidacy came strongly to his defence. The entire Labour party, which for months had been tearing itself apart, rallied to Khan's side. For many on the London left, stopping Goldsmith from becoming mayor stopped being important and became vital.

"The Tories have to be careful," a source close to Khan had told me a couple of months before.

"The extremism stuff might work with parts of their core vote, but it also motivates a section of our own core vote as well."

As the former leader of the London Assembly Tories, Andrew Boff, told Newsnight shortly after the polls closed last Thursday: "I don't think it was dog-whistle because you can't hear a dog whistle. Everybody could hear this."

Within hours, Boff would be joined by other senior Tories in denouncing Goldsmith's campaign. "It was poisonous," one senior London Tory told me as the results came in. "It was a mistake. I've spent a long time in London visiting all different communities and I've always been very courteously received. I'm worried now that I won't be. It's done a lot of damage."

Another Tory big beast told journalists that Goldsmith's campaign had been fatally misjudged. Zac failed, he said, because he was trying to blow "a dog whistle in a city where there’s no dog."

By the time the London mayor result finally came in, Goldsmith looked utterly broken, with just a small fraction of his team still sat in the audience to watch him make his concession speech. In the following days he would continue to suffer a wave of attacks for the way he ran his campaign, even from his own family.

"Sad that Zac's campaign did not reflect who I know him to be- an eco friendly, independent- minded politician with integrity," tweeted Goldsmith's sister Jemima.

But if Goldsmith deserved to lose, then Khan arguably deserved to win. At the start of the campaign, many in the Labour party had doubted Khan's abilities. Faced with the articulate and good-looking Conservative candidate and a ruthless campaign operation, Khan's internal party critics believed their man would crumble under the pressure.

It never happened. In fact, far from crumbling, Khan grew in confidence and strength throughout the campaign. Although still a cautious media performer, Khan is a different politician from the unassuming former minister who first turned up at Labour mayoral hustings almost a year ago.

Time will tell whether he makes a good mayor, but few elected British politicians have ever passed such a tough application process as Khan did during this campaign. It's one which will stand him in good stead for the challenges he now faces.

Adam Bienkov is the deputy editor of Politics.co.uk

The opinions in politics.co.uk's Comment and Analysis section are those of the author and are no reflection of the views of the website or its owners