Office 365 API for Laravel.

dev-master 2017-04-22 19:14 UTC


17th May - We are aware of an issue with refresh tokens in this package which causes a loop in some cases once a 60 minute timeout has occured. This package should not be considered production-ready.

Application Setup and Login

  1. Generate an ID and secret (for two separate applications, live and test) at https://apps.dev.microsoft.com/#/appList.

  2. Set these in .env:

  1. Add a Web platform and set the redirect URIs to:


  1. Secure the site locally using valet secure.

  2. Run php artisan make:auth and add the following to routes/web.php. You can delete all controllers in Controllers/Auth (except LoginController) if you will only be using O365 login.

Route::get('/login', 'Auth\LoginController@showLoginForm');
Route::get('/o365', 'Auth\LoginController@processO365Login');
Route::get('/logout', 'Auth\LoginController@logout');
  1. Use the following as a login URL:
<a href="<?= \Centu\O365\Authenticator::getLoginUrl(); ?>">Click here to login to Office 365</a>
  1. Create the appropriate method in LoginController based on the below (n.b. flash messages are using laracasts/flash package but you can replace these with any flash messages you wish):
public function processO365Login(Request $request)
    $tokens = \Centu\O365\Authenticator::getTokenFromAuthCode($request->code);
    if (!isset($tokens['access_token'])) {
        flash('Your login attempt expired; please try login again.', 'danger');
        return redirect('/login');

    $accessToken = $tokens['access_token'];
    $refreshToken = $tokens['refresh_token'];

    session(['accessToken' => $accessToken]);
    session(['refreshToken' => $refreshToken]);

    $expiration = time() + $tokens['expires_in'] - 300;
    session(['tokenExpiry' => $expiration]);

    $user = \Centu\O365\Authenticator::getUser($accessToken);

    if ($user) {
        $appUser = User::where('email', strtolower($user['EmailAddress']))->first();
        if ($appUser) {
            Auth::login($appUser, true);
            return redirect('/');
        } else {
            flash('No user could be found with the email address ' . $user['EmailAddress'], 'danger');
            return redirect('/login');
    } else {
        flash('There was a problem logging you into Office 365, please try again.', 'danger');
        return redirect('/login');