The speech served as a bookend to a 2009 address Mr. Obama delivered at Cairo University, where he called for “a new beginning between the United States and Muslims around the world.” In Baltimore, the president did not talk about intractable international conflicts like the Israeli-Palestinian dispute and focused instead on the more prosaic reality of vandalized mosques and bullied American Muslim children.

“These children are just like mine,” Mr. Obama said. “And the notion that they would be filled with doubt and questioning their places in this great country of ours at a time when they’ve got enough to worry about — it’s hard being a teenager already — that’s not who we are.”

Although President George W. Bush visited a mosque in Washington within six days of the Sept. 11, 2001, terrorist attacks to reassure American Muslims, Mr. Obama, a Christian, brushed aside requests for a visit for years in part because 43 percent of Republicans and 29 percent of Americans think he is a Muslim, according to a CNN/ORC poll last September. Aides feared a mosque visit would feed into that perception.

But in the final year of his presidency, Mr. Obama has lost much of his reticence in addressing issues like race, addiction and religion, often in very personal terms. Administration officials said there had been little internal debate about Mr. Obama visiting an American mosque since talk about it began at the White House last fall.

In an aside that drew considerable laughter, Mr. Obama told the crowd at the mosque that controversy over a president’s religion is not new. “By the way, Thomas Jefferson’s opponents tried to stir things up by suggesting he was a Muslim — so I was not the first,” he said, adding: “I’m in good company.”