xauth and sudo

The below incantation will transfer X authority cookies from one user to another when using sudo. Maybe there is a better way?

There definately is a security risk between “xauth nextract” and “rm” where the security cookie is written to disk.

export PORT=`echo $DISPLAY | sed -e 's|.*:||' -e 's|\.[0-9]||'`
rm -f /tmp/${LOGNAME}:${PORT}_xauth
touch /tmp/${LOGNAME}:${PORT}_xauth
chmod 0666 /tmp/${LOGNAME}:${PORT}_xauth
/usr/openwin/bin/xauth nextract /tmp/${LOGNAME}:${PORT}_xauth `/usr/openwin/bin/xauth list | awk /\`hostname\`.*:$PORT/'{print $1}'`
sudo -s -u oracle
export XAUTHORITY=`getent passwd oracle | awk -F: '{print $6}'`/.Xauthority
/usr/openwin/bin/xauth nmerge /tmp/${SUDO_USER}:${PORT}_xauth
rm -f /tmp/${SUDO_USER}:${PORT}_xauth
xclock # or whatever X program
/usr/openwin/bin/xauth remove `/usr/openwin/bin/xauth list | awk /\`hostname\`.*:$PORT/'{print $1}'`

Read more of this post