Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
rjmedin opened this issue Dec 16, 2022 · 11 comments
Open

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

rjmedin opened this issue Dec 16, 2022 · 11 comments

Comments

@rjmedin
Copy link

rjmedin commented Dec 16, 2022

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
Copy link

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
Copy link
Author

rjmedin commented Dec 23, 2022

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
Copy link

gabriel-tandil commented Dec 26, 2022

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
Copy link
Author

rjmedin commented Dec 26, 2022

@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
Copy link
Author

rjmedin commented Dec 26, 2022

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
Copy link

@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
Copy link
Author

rjmedin commented Dec 28, 2022

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
Copy link

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
Copy link
Author

rjmedin commented Dec 29, 2022

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
Copy link

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

@AKang9
Copy link

AKang9 commented Sep 29, 2024

@rjmedin Is the problem solved when imap2_open displays the message "failed to authenticate to IMAP server :A0001 NO authenticate failed"? I am now asking outlook imap to also encounter this problem.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants