I'm trying to retrieve the expiration date on a certificate that is only on the user's keychain, so that we can notify the user when their certificate is expiring.
After many failed attempts, I've concluded that the best way to do so is to run the security command under the user's PID.
declare -x LoginWindowPID="$(/bin/ps -axww | /usr/bin/grep loginwindo[w] | /usr/bin/awk '/console/{print $1;exit}')"
certificate=$(/bin/launchctl bsexec "${LoginWindowPID:?}" /usr/bin/sudo -u "$consoleuser" security find-certificate -c "CERT NAME")
This seems to work for about half the computers, but the other half returns that the certificate could not be found because the only available keychains are the System's.
Any ideas on how to fix this, or why the script can't access some user's keychains?