A man tried to rape a woman aboard a subway train in Brooklyn — but a courageous straphanger rushed to her rescue.

Alvaro Denica, 40, was allegedly attacking the 28-year-old woman at about 11:40 a.m. Wednesday on a 3 train approaching the Bergen Street station in Park Slope when Maurice Osborne jumped in to save her, sources said.

“I beat him up,” Osborne told The Post, wearing a bandage for a head cut sustained in the fight. “Once he submitted, I grabbed him by the shirt and dragged him to the police station two blocks away.”

Prosecutors said Denica was pleasuring himself in the last car of the train before he grabbed the woman, shoved her to the floor and tried to sexually assault her.

Osborne, who was riding in the second-to-last car, noticed the commotion and ran to help.

“When I looked back, I saw he was on top of her,” Osborne said.

“She said he was about to rape her — that’s when I beat him up. All he said was, ‘I didn’t do anything.’”

Osborne managed to subdue the suspect and haul him to the nearby 78th Precinct station house.

Denica allegedly admitted he had been pleasuring himself on the train but denied he had attempted to rape the woman, sources said.

In Brooklyn Criminal Court on Thursday night, he was charged with assault as a sexually motivated felony and attempted sexual abuse. He was held in lieu of $150,000 bond.