Last active
October 13, 2015 18:21
-
-
Save jeffsrepoaccount/455a0e93a8fee5830515 to your computer and use it in GitHub Desktop.
Middleware for integrating an OAuth2 Resource Server with an Authorization server built with lucadegasperi/oauth2-server-laravel on Laravel 5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php namespace App\Oauth2\Middleware; | |
use Closure; | |
use Illuminate\Http\Request; | |
use App\User; | |
use League\OAuth2\Server\Exception\AccessDeniedException; | |
use League\OAuth2\Server\Exception\InvalidRequestException; | |
use League\OAuth2\Server\ResourceServer; | |
use Exception; | |
class OauthAccess | |
{ | |
public function __construct( | |
ResourceServer $server, | |
User $user | |
) { | |
$this->server = $server; | |
$this->user = $user; | |
} | |
public function handle(Request $request, Closure $next) | |
{ | |
try { | |
if(!$this->server->isValidRequest(true)) { | |
abort(400); | |
} | |
$this->setUser($request); | |
} catch( InvalidRequestException $e ) { | |
\Log::notice('Bad API Access Attempt, No access token', [ | |
]); | |
abort(400); | |
} catch( AccessDeniedException $e ) { | |
\Log::notice('Bad API Access Attempt, Invalid access token', [ | |
'token' => str_replace('Bearer ', '', $request->header('Authorization')), | |
]); | |
abort(401); | |
} | |
return $next($request); | |
} | |
protected function setUser($request) | |
{ | |
$userId = $this->server->getAccessToken()->getSession()->getOwnerId(); | |
$user = $this->user->findOrFail($userId); | |
// Closure will encapsulate preceeding $user object for the | |
// remainder of the request. | |
$request->setUserResolver(function() use($user) { | |
return $user; | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment