"There was heavy fighting this morning," said Mohamed Haji Ali, a Somali military commander, confirming the attack to local media without providing details of casualties.
Residents said the attack left bodies of government soldiers scattered on the ground while al-Shabab fighters looted the base, stealing vehicles and weapons.
"There were dead bodies around the military camp, and I counted about eight of them from the Somali military, but it could be more than that," said Abdulahi Muktar.
Another resident described hearing two large blasts followed by heavy gunfire.
"This attack was very sophisticated, with the militants raiding the base from three directions. There were two huge blasts presumably suicide bombs," said Mohamed Malim.
Abdiasis Abu Musab, al-Shabab's military operations spokesman, claimed responsibility for the brazen assault.
"After morning prayer today, two mujahideen rammed into Barire military base with suicide car bombs. We killed 17 soldiers and took seven technical vehicles," he told Reuters news agency, referring to pick-up trucks mounted with machine guns.
"The other soldiers ran helter-skelter into the woods. We now control the base and the village," said Musab.
Barire is 50km southwest of Mogadishu.
Al-Shabab aims to topple the government in Mogadishu and impose its strict interpretation of Islam in the country.
Somalia has been at war since 1991 when clan-based warlords overthrew dictator Siad Barre and then turned on each other.
The al-Qaeda-linked group was driven out of the capital in 2011, but still carries out frequent attacks on security and government targets, as well as civilians. It also targets African Union peacekeeping troops.
Ali Nur - deputy governor of Lower Shabelle region, where Barire is located - confirmed the fighting but gave no more details on how many soldiers were killed.
Other residents in Barire also confirmed the attack.
"First we heard two huge blasts at the base, and then heavy exchange of gunfire followed. Now it looks like the fighting died down," said Ali Farah from Barire village.
Friday's attack is the latest in violence-plagued Somalia. On Thursday, a car bomb blast near a popular market in Mogadishu killed at least seven people.
No group claimed responsibility, but the area has previously suffered attacks by al-Shabab.
Two weeks ago the armed group struck an army base at a border town with Kenya. Three weeks ago al-Shabab hit the southern port city of Kismayu, killing at least 43 people in both incidents.
Source: News agencies