Skip to content

Instantly share code, notes, and snippets.

@jeffsrepoaccount
Created September 6, 2015 12:13
Show Gist options
  • Save jeffsrepoaccount/25fade0d1cbe6daff4ae to your computer and use it in GitHub Desktop.
Save jeffsrepoaccount/25fade0d1cbe6daff4ae to your computer and use it in GitHub Desktop.
Middleware for validating OAuth requests to the resource server
<?php namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use League\OAuth2\Server\Exception\AccessDeniedException;
use League\OAuth2\Server\Exception\InvalidRequestException;
use League\OAuth2\Server\ResourceServer;
use Exception;
class OauthAccess
{
protected $errors;
public function __construct(ResourceServer $server)
{
$this->server = $server;
}
public function handle(Request $request, Closure $next)
{
try {
if(!$this->server->isValidRequest(true)) {
return $this->respondWithErrorStatus(400);
}
} catch( InvalidRequestException $e ) {
return $this->respondWithErrorStatus(400);
} catch( AccessDeniedException $e ) {
return $this->respondWithErrorStatus(401);
}
return $next($request);
}
protected function respondWithErrorStatus($status)
{
// n.b. example error handling
switch($status) {
case 400: $message = 'Bad request'; break;
case 401: $message = 'Unauthorized'; break;
case 403: $message = 'Forbidden'; break;
case 500: default: $message = 'Internal Server Error'; break;
}
return response()->json(['message' => $message], $status);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment