\makeatletter
\let\oldref\ref
\def\ref#1{%
\expandafter\ifx\csname R@#1\endcsname\relax
\global\expandafter\let\csname R@#1\endcsname\@empty
\immediate\write\@auxout{%
\string\gappto\string\ReferencedIDs{\trim@spaces{#1},}%
}%
\fi
\oldref{\trim@spaces{#1}}%
}
\def\ReferencedIDs{}
\makeatother