javanile / php-imap2

PHP IMAP with OAUTH2
https://php-imap2.javanile.org/
GNU General Public License v3.0
48 stars 28 forks source link

How can get token access autorefresh from cli or php library? #38

Open rjmedin opened 1 year ago

rjmedin commented 1 year ago

Exist any method not graphic to get token from cli? I need read mails from 2 accounts, one gmail an other outlook. The process to read is run in a crontab. With tokens limited of google developers get from https://php-imap2.javanile.org/google-playground.html run very well but the tokens expire and I don't know how to renew it from the cli

gabriel-tandil commented 1 year ago

for outlook https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow?source=recommendations#refresh-the-access-token for google is similar

rjmedin commented 1 year ago

Hola @gabriel-tandil gracias por responder. Seguí los pasos del articulo que me pasaste hasta el consentimiento desde la Azure Active Directory. Es necesario el paso de "Registrar entidades principales de servicio en Exchange"?

Para google pude hacerlo sin tantos inconvenientes, pero con Microsoft se me ha hecho dificil. Si me puedes echar una mano te lo agradeciería, ya llevo mucho días en esto

gabriel-tandil commented 1 year ago

Hola amigo @rjmedin , no se cual es ese paso al que te referís, pero no creo que sea necesario porque no hice algo que suene como eso. si continuas con problemas te puedo pasar el fragmento de código que uso para refrescar el token cuando este se vence. saludos

rjmedin commented 1 year ago

@gabriel-tandil gracias. El problema es que el correo con el que estaba probando no tenía suscripción de microsoft exchange online. Ahora si me autoriza con el token que genero. Solo me falta el refrescar token y ahora voy con eso pero pudieras pasarme ese fragmento sería genial jeje. Saludos y bendiciones.

rjmedin commented 1 year ago

Chicos acá compartí como quedó mi solucion final. Ojala pueda servir a quienes como yo, pasaron varios días tratando de hacer una solucion basada en php ya que la documentacion oficial no la proporciona. Esta solucion combinada con el imap2 me ayuddará con lo que necesito. Gracias @gabriel-tandil y @francescobianco. Luego comparto la de gmail.

https://stackoverflow.com/questions/74921766/php-oauth2-0-conection-with-microsoft-outlook-office365

gabriel-tandil commented 1 year ago

@rjmedin I share with you my code for the token renewal, it is only a fragment but I hope it will be useful to guide you.

    public static function renovarToken(CuentasMail $cuenta){
        $login= CadenaTipoMedioLogin::findOne(["identificador"=>$cuenta->idCuentasMail,"idTipoMedioDeContacto"=>TipoMedioDeContacto::CTE_idTipoMedioDeContacto_mail]);

        $refresh_token=null;
        $token = $login->getToken();
        if ($token!=null && property_exists($token,'refresh_token')){
            $refresh_token=$token->refresh_token;
        }
        // pedir token con refresh token
        $peticion = [
            'scope'=>self::ALCANCES,
            'grant_type'=>'refresh_token',
            'client_secret'=>self::CLIENT_SECRET,
            'client_id' =>self::CLIENT_ID,
            'refresh_token' => $refresh_token,
        ];
        $respuestaToken = json_decode(self::curlPost(self::URL_BASE.'/token',$peticion), true);

        Bitacora::registrarEnBitacora(json_encode($respuestaToken), Bitacora::TIPO_DATO_DATOS_RECIBIDOS, Bitacora::TIPO_PROCESO_GENERAL, null, __CLASS__, __FUNCTION__, 'obtener token');

        if (isset($respuestaToken['access_token'])) { // you got a valid authorization token

            $login->setToken($respuestaToken);

            $login->save(false);
        }else
            throw new \Exception("sin informacion");

    }
rjmedin commented 1 year ago

Chicos, una pregunta. Tengo una cuenta de empresa que es con la cual hice la conexion OAuth2 para microsoft, agregué un usuario externo a mi organización y puedo generar token tranquilamente. Pero al momento de hacer la conexión con el Imap2 me da "Can not authenticate to IMAP server: A0001 NO AUTHENTICATE failed.".

Con el usuario dueño de la aplicación me autentica bien, pero con uno externo no puedo. Alguien sabe si debo configurar algo extra en el Azure?

gabriel-tandil commented 1 year ago

Please write in English so that the information provided here is useful for most people (all the project documentation is in English).

That as you mention it did not happen to me. Yes at one point with an enterprise account the oauth flow was interrupted indicating that the account administrator had to give permission for users to request those scopes. Also with enterprise accounts I found that the user had no access requesting the connection for the default mailbox (the token was obtained fine but it was not possible to access via imap), which I solved by removing the mailbox part of the imap connection string. But those are all the problems I ran into with microsoft enterprise accounts.

rjmedin commented 1 year ago

excuse me @gabriel-tandil this is my imap_open:

`$mailbox = '{outlook.office365.com:993/imap/ssl}INBOX';

$imap_conn = @imap2_open($mailbox, $imap_email, $accessToken, OP_XOAUTH2);`

Do you say the "INBOX" at the end of string?

Note: I have a account with all privileges and conect success. But I need conect other account of other bussiness that not have privileges. The app was register by the admin of bussiness for this user. I can generate tonkens but when I want exec imap2_open say the message "Can not authenticate to IMAP server: A0001 NO AUTHENTICATE failed."

gabriel-tandil commented 1 year ago

Exactly @rjmedin, without INBOX With INBOX it did work for the free ...@outlook.com accounts but for the company accounts I had to take it out, and it works fine. I mention this in a comment in #37