I followed the laracasts tutorial on Socialite. My ultimate aim is to connect to azure ad, but I was having problems with various aspects of that so I thought I'd start with his github tutorial and get it working in principle first. I was fine until I tried to use middleware - now I get caught in infinite redirect loops. If I break out of the loop and go to the homepage, it has successfully logged me in - but obviously the user won't know that and will think it's failed.
Any help would be greatly appreciated.
Ed.
AuthController:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\AuthenticateUser;
class AuthController extends Controller {
public function login(AuthenticateUser $authenticateUser, Request $request) {
$authenticateUser->execute($request->has('code'), $this);
return \Socialite::with('github')->redirect();
}
public function logout() {
if (\Auth::check()) \Auth::logout();
return view('auth.loggedout');
}
}
AuthenticateUser:
<?php
namespace App;
use Illuminate\Contracts\Auth\Guard;
use Laravel\Socialite\Contracts\Factory as Socialite;
use App\Repositories\UserRepository;
use Request;
class AuthenticateUser {
private $socialite;
private $auth;
public function __construct(UserRepository $users, Socialite $socialite, Guard $auth) {
$this->users = $users;
$this->socialite = $socialite;
$this->auth = $auth;
}
public function execute($hasCode) {
if (!$hasCode) {
return $this->getAuthorizationFirst();
}
$user = $this->users->findbyEmail($this->getUser());
$this->auth->login($user, true);
return redirect('/');
}
public function getAuthorizationFirst() {
return $this->socialite->driver('github')->redirect();
}
public
function getUser() {
return $user = $this->socialite->driver('github')->user();
}
}
routes.php:
Route::get('o365/connect', 'AuthController@login');
Route::get('o365/callback', 'AuthController@login');
Route::get('auth/logout', 'AuthController@logout');
Authenticate Middleware:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Auth\Guard;
class Authenticate {
/**
* The Guard implementation.
*
* @var Guard
*/
protected $auth;
/**
* Create a new filter instance.
*
* @param Guard $auth
* @return void
*/
public function __construct(Guard $auth) {
$this->auth = $auth;
}
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next) {
if ($this->auth->guest()) {
if ($request->ajax()) {
return response('Unauthorized.', 401);
} else {
return redirect()->guest('o365/connect');
}
}
if (\Auth::check()) {
return $next($request);
}
}
}
via Chebli Mohamed
Aucun commentaire:
Enregistrer un commentaire