How to use new microsoft graph api to log users in to yii site

768 Views Asked by At

I'm creating a site that needs an oauth authorization through microsoft. In yii/authclient there's only live client and it is not working anymore.

I tried to write my own but something goes wrong. As far as I understood my AuthAction doesn't see clientId and returns 404 exception without text. Here's my code of the auth client.

What I get What I get

AuthAction class method run (it's default) AuthAction class method run (it's default)

class Office365OAuth extends OAuth2
{
    public $authUrl = 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize';
    public $tokenUrl = 'https://login.microsoftonline.com/common/oauth2/v2.0/token';
    public $apiBaseUrl = 'https://login.microsoftonline.com/common/oauth2/v1.0';

    public $scope = null;

    public function init()
    {
        parent::init();
        if ($this->scope === null)
        {
            $this->scope = 'https://graph.microsoft.com/User.Read';
        }
    }

    /**
     * Overrides default function to fix malformed url
     */
    public function getReturnUrl()
    {
        return $this->returnUrl;
    }

    protected function defaultName()
    {
        return 'office365';
    }

    protected function defaultTitle()
    {
        return 'Office365';
    }

    /**
     * For popup mode
     */
    protected function defaultViewOptions()
    {
        return [
            'popupWidth' => 800,
            'popupHeight' => 500,
        ];
    }

    /**
     * Gets new auth token to replace expired one.
     */
    protected function initUserAttributes()
    {
        return $this->api('me', 'GET');
    }
}

So, how can I authenticate through MS graph?

1

There are 1 best solutions below

0
On

The yii\authclient package requires using the returnUrl having a request param authclient=live, e.g. https://example.com/site/auth?authclient=live

However, Azure prohibits request params in the returnUrl. Therefore, to make yii\authclient works with Azure, i.e., the returnUrl as https://example.com/site/auth/live. You need to prettify the url with request param as follows:

In config/main.php

'components' => [
     'urlManager' => [
         'class' => 'yii\web\UrlManager',
         'enablePrettyUrl' => true,
         'rules' => [
             'site/auth/<authclient>' => 'site/auth'
         ]
     ]
]

In controllers/SiteController.php,

public function actions()
{
    return [
        'auth' => [
            'class' => 'yii\authclient\AuthAction',
            'successCallback' => [$this, 'onAuthSuccess']
        ]
    ];
}

...

public function onAuthSuccess($client) {
    // get user data from client
    $userAttributes = $client->getUserAttributes();
    // DO YOUR THING
}