dcblogdev / laravel-microsoft-graph

Laravel package for Microsoft Graph API (Microsoft365)
https://dcblog.dev/docs/laravel-microsoft-graph
Other
120 stars 51 forks source link

Get users email without auth #40

Closed RabieAli95 closed 1 year ago

RabieAli95 commented 1 year ago

Hi, I'm trying to get my personal emails by your pkg, this is my code:

in .env :

MSGRAPH_CLIENT_ID=01306e60-4f2d-425cxxxxxxxxxx  // Application (client) ID from 'aad.portal.azure.com'
MSGRAPH_SECRET_ID=f3cb7221-4a86-468cxxxxxxxxxxx // Object ID  from 'aad.portal.azure.com'
MSGRAPH_TENANT_ID=9597912b-442e-4ce3xxxxxxxxxx // Directory (tenant) ID from 'aad.portal.azure.com'
Route::get('/', function () {
    $emails = MsGraph::getEmails();
    dd($emails);
});

I got error

Object of class Illuminate\Routing\Redirector could not be converted to string
timvanuum commented 1 year ago

Having the same issue, did you manage to solve it?

timvanuum commented 1 year ago

I think the problem is in here. For a admin call there is no need to redirect for login. But if there is no token in the database yet then a login redirect is triggered.

So if I generate my token and put in the database it works.

public function getAccessToken($returnNullNoAccessToken = null)
    {
        //use id if passed otherwise use logged-in user
        $token = MsGraphToken::where('user_id', null)->first();

        // Check if tokens exist otherwise run the oauth request
        if (! isset($token->access_token)) {
            //don't redirect simply return null when no token found with this option
            if ($returnNullNoAccessToken == true) {
                return null;
            }

            return redirect(config('msgraph.redirectUri'));
        }

        // Check if token is expired
        // Get current time + 5 minutes (to allow for time differences)
        $now = time() + 300;
        if ($token->expires <= $now) {
            // Token is expired (or very close to it) so let's refresh

            $params = [
                'grant_type'    => 'authorization_code',
                'scope'         => 'https://graph.microsoft.com/.default',
                'client_id'     => config('msgraph.clientId'),
                'client_secret' => config('msgraph.clientSecret'),
                'grant_type'    => 'client_credentials',
            ];

            $token = $this->dopost(config('msgraph.tenantUrlAccessToken'), $params);

            $newToken = $this->storeToken($token->access_token, '', $token->expires_in);

            return $newToken->access_token;
        } else {
            // Token is still valid, just return it
            return $token->access_token;
        }
    }

For testing now I have added this:

    $guzzle = new \GuzzleHttp\Client();
    $url = config('msgraph.tenantUrlAccessToken');
    $token = json_decode($guzzle->post($url, [
        'form_params' => [
            'client_id' => config('msgraph.clientId'),
            'client_secret' => config('msgraph.clientSecret'),
            'scope' => 'https://graph.microsoft.com/.default',
            'grant_type' => 'client_credentials',
        ],
    ])->getBody()->getContents());
    $accessToken = $token->access_token;

    MsGraphToken::updateOrCreate(['user_id' => null], [
        'access_token'  => $accessToken,
        'expires'       => now()->addYears(10),
        'refresh_token' => null,
    ]);
MahaEast commented 1 year ago

I have an issue where users has to logout and login to be the correct user, when changing computer, machine and browser. Otherwise it is the last known user who is logged in when loading the application.

Do You guys know that issue?

dcblogdev commented 1 year ago

Yes, I'm working on a fix for this, it will be ready shortly. Part of a bigger re-write.

dcblogdev commented 1 year ago

I've just released https://github.com/dcblogdev/laravel-microsoft-graph/releases/tag/v3.2.0. the only changes required are updating the listener to the following if you're using the provided listener.

<?php

namespace App\Listeners;

use App\Models\User;
use Dcblogdev\MsGraph\MsGraph;
use Illuminate\Support\Facades\Auth;

class NewMicrosoft365SignInListener
{
    public function handle($event)
    {
        $user  = User::firstOrCreate([
            'email' => $event->token['info']['mail'],
        ], [
            'name'     => $event->token['info']['displayName'],
            'email'    => $event->token['info']['mail'] ?? $event->token['info']['userPrincipalName'],
            'password' => '',
        ]);

        (new MsGraph())->storeToken(
            $event->token['accessToken'],
            $event->token['refreshToken'],
            $event->token['expires'],
            $user->id,
            $user->email
        );

        Auth::login($user);
    }
}

Also updated the docs to make them more clear.