normunds.pauders's avatar

Laravel default auth and Microsoft graph, oauth.

Hi, I want create autentication with Microsoft graph using 0365. I created that I can get data from graph, but I dont I understand how I cant transfer these data to default laravel autenfication. Can anyone please help with second part? What I have done till now:

1.I created project using this command:

composer create-project --prefer-dist laravel/laravel="5.8.*"

2.I created default Laravel autentication:

php artisan make:auth

3.I did these step without last calendar funcionality: https://docs.microsoft.com/en-us/graph/tutorials/php?tutorial-step=1

4.I found this article and did that what was wrote there: https://laracasts.com/discuss/channels/laravel/authenticate-users-based-on-microsoft-oauth-login

      try {
                // Make the token request
                $accessToken = $oauthClient->getAccessToken('authorization_code', [
                    'code' => $authCode
                ]);

                $graph = new Graph();
                $graph->setAccessToken($accessToken->getToken());


                $user = $graph->createRequest('GET', '/me')
                    ->setReturnType(Model\User::class)
                    ->execute();

                // HERE YOU CAN SAVE THE USER IN THE DB + LOGIN WITH LARAVEL

                //https://stackoverflow.com/questions/38268137/laravel-5-2-split-string-first-name-last-name
                $split = explode(" ", $user->getDisplayName());
                $firstname = array_shift($split);
                $lastname  = implode(" ", $split);



                $user = User::firstOrCreate([
                    'email' => $user->getmail()
                ], [
                    'surname' => $lastname,
                    'name' => $firstname,
                    'password' => 'secret'
                ]);
              auth()->login($user);





                $tokenCache = new TokenCache();
                $tokenCache->storeTokens($accessToken, $user);
                //noradits skats uz kuru doties
                return redirect('/');
            }

But now I am stuck in 4. step. Laravel create user, if does not exists, but all the time I get this error

Call to undefined method App\User::getDisplayName()
(1/1) BadMethodCallException
Call to undefined method App\User::getDisplayName()

in ForwardsCalls.php line 50
at Model::throwBadMethodCallException('getDisplayName')
in ForwardsCalls.php line 36
at Model->forwardCallTo(object(Builder), 'getDisplayName', array())
in Model.php line 1618
at Model->__call('getDisplayName', array())
in TokenCache.php line 12
at TokenCache->storeTokens(object(AccessToken), object(User))
in AuthController.php line 106
at AuthController->callback(object(Request))
at call_user_func_array(array(object(AuthController), 'callback'), array(object(Request)))
in Controller.php line 54
at Controller->callAction('callback', array(object(Request)))
in ControllerDispatcher.php line 45
at ControllerDispatcher->dispatch(object(Route), object(AuthController), 'callback')
in Route.php line 219

It seems that default auth seassion dont work. ☹ When I use method:

User::firstOrCreate

I add

use App\User;

to AuthController.php

And that's look my route file:

Route::get('/', function () {
    return view('welcome');
});


Route::get('/signin', 'AuthController@signin');
Route::get('/callback', 'AuthController@callback');
Route::get('/signout', 'AuthController@signout');

Auth::routes();
Route::get('/home', 'HomeController@index')->name('home');

User.php modul file:

<?php

namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $table = 'users';

    protected $fillable = [
        'name', 'surname', 'password', 'email', 'statuss'
    ];





}

p.s. I know similar article is there, but I hope this article will hold the full instruction, what maybe will help for me and others. For now I can't figure out what is wrong.

0 likes
2 replies
normunds.pauders's avatar

It seems, I find solution:

$graph = new Graph();
                $graph->setAccessToken($accessToken->getToken());


                $user = $graph->createRequest('GET', '/me')
                    ->setReturnType(Model\User::class)
                    ->execute();

                $tokenCache = new TokenCache();
                $tokenCache->storeTokens($accessToken, $user);
                // HERE YOU CAN SAVE THE USER IN THE DB + LOGIN WITH LARAVEL

                //https://stackoverflow.com/questions/38268137/laravel-5-2-split-string-first-name-last-name
                $split = explode(" ", session('userName'));
                $firstname = array_shift($split);
                $lastname  = implode(" ", $split);



                $user = User::firstOrCreate([
                    'email' =>  session('userEmail')
                ], [
                    'surname' => $lastname,
                    'name' => $firstname,
                    'password' => 'secret'
                ]);
              auth()->login($user);
//                dd($user);





                //redirect to home
                return redirect('/home');

I first save tokens, then i get session data and store user. How you think it's ok?

dorqa95's avatar

The error was because of when you get data from the api in the official example (https://github.com/microsoftgraph/msgraph-sdk-php) there is a setReturnType(User::class) method, where User class is not your Model/User model, but the Microsoft\Graph\Model\User class. You can import with this:

use Microsoft\Graph\Model\User as GraphUser;

and in the code just modify the return type for that:

(new Graph())->setAccessToken($accessToken)
    ->createRequest('GET', '/me')
    ->setReturnType(GraphUser::class)
    ->execute();

Please or to participate in this conversation.