Skip to content

Commit

Permalink
Fixes for 6.*
Browse files Browse the repository at this point in the history
  • Loading branch information
PrasadChinwal committed Oct 27, 2020
1 parent da8ad0e commit 9052128
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 90 deletions.
9 changes: 6 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
# Note

> THis package is exact replica of [arietimmerman/laravel-oauth-introspect-middleware](https://github.com/arietimmerman/laravel-oauth-introspect-middleware) with support for Laravel 7.x.
Especially for a microservices architecture, authentication and authorization functions should be delegated. Protecting resources is best done by implementing the web services as a pure OAuth2 resource server, relying on token verification on a remote authorization server.

Expand Down Expand Up @@ -33,9 +36,9 @@ and add the MiddleWare in your `App/Http/Kernel.php`
protected $routeMiddleware = [
// [..]
'verifyaccesstoken' => \ArieTimmerman\Laravel\OAuth2\VerifyAccessToken::class,
// [..]
// [..]
];
~~~
~~~

publish the configuration

Expand All @@ -57,7 +60,7 @@ AUTHORIZATION_SERVER_TOKEN_URL="${AUTHORIZATION_SERVER_URL}/oauth/token"
# The OAuth2 Introspection endpoint https://tools.ietf.org/html/rfc7662
AUTHORIZATION_SERVER_INTROSPECT_URL="${AUTHORIZATION_SERVER_URL}/oauth/introspect"

# Optional configuration for requesting an OAuth2 access tokens using the implicit grant flow
# Optional configuration for requesting an OAuth2 access tokens using the implicit grant flow
AUTHORIZATION_SERVER_AUTHORIZATION_URL="${AUTHORIZATION_SERVER_URL}/oauth/authorize"
AUTHORIZATION_SERVER_REDIRECT_URL=https://my.machine.dom
~~~
Expand Down
124 changes: 37 additions & 87 deletions src/VerifyAccessToken.php
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
<?php

/**
* Middleware for verifying the Bearer OAuth2 access token as provided in the HTTP Authorization-header.
* Middleware for verifying the Bearer OAuth2 access token as provided in the HTTP Authorization-header.
*/

namespace ArieTimmerman\Laravel\OAuth2;

use Closure;
Expand All @@ -14,137 +15,86 @@

class VerifyAccessToken
{

private $client = null;

private function getClient()
{
if ($this->client == null) {
$this->client = new \GuzzleHttp\Client();
}

return $this->client;
}

public function setClient(\GuzzleHttp\Client $client)
{
$this->client = $client;
}

/**
*/
protected function getIntrospect($accessToken)
{
$guzzle = $this->getClient();

$tries = 0;
do{

try {
$tries++;
$response = $guzzle->post(
config('authorizationserver.authorization_server_introspect_url'), [
'form_params' => [
'token_type_hint' => 'access_token',

// This is the access token for verifying the user's access token
'token' => $accessToken
],
'headers' => [
'Authorization' => 'Bearer ' . $this->getAccessToken()
]
]
);
}catch(RequestException $e){

// Access token might have expired, just retry getting one
\Cache::forget('accessToken');

if($tries == 2) {
throw $e;
}

}

}while($tries < 2);

return json_decode(( string ) $response->getBody(), true);
}

protected function getAccessToken()
{
$accessToken = Cache::get('accessToken');

if (! $accessToken) {

$guzzle = $this->getClient();

try {
$response = $guzzle->post(
config('authorizationserver.authorization_server_token_url'), [
'form_params' => [
'grant_type' => 'client_credentials',
'client_id' => config('authorizationserver.authorization_server_client_id'),
'client_secret' => config('authorizationserver.authorization_server_client_secret'),
'scope' => ''
]
]
config('authorizationserver.authorization_server_introspect_url'), [
'form_params' => [
'token' => $accessToken,
'client_id' => config('authorizationserver.authorization_server_client_id'),
'client_secret' => config('authorizationserver.authorization_server_client_secret'),
],
]
);

$result = json_decode(( string ) $response->getBody(), true);

if ($result && isset($result ['access_token'])) {

$accessToken = $result ['access_token'];

\Cache::add('accessToken', $accessToken, intVal($result ['expires_in']) / 60);
} else {

throw new InvalidEndpointException("Did not receive an access token");
}
} catch(RequestException $e) {

// Access token might have expired, just retry getting one
\Cache::forget('accessToken');
}
return $accessToken;

return json_decode(( string ) $response->getBody(), true);
}

/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next, ...$scopes)
{
$authorization = $request->header('Authorization');

if (strlen($authorization) == 0) {
throw new InvalidInputException("No Authorization header present");
}

$receivedAccessToken = preg_replace('/^Bearer (.*?)$/', '$1', $authorization);

// Just to be sure it is really an access token
if (strlen($receivedAccessToken) <= 1) {
throw new InvalidInputException("No Bearer token in the Authorization header present");
}

// Now verify the user provided access token
try {
$result = $this->getIntrospect($receivedAccessToken);

$result = $this->getIntrospect($receivedAccessToken);
if (! $result ['active']) {

throw new InvalidAccessTokenException("Invalid token!");
} else if ($scopes != null) {

if (! \is_array($scopes)) {
$scopes = [
$scopes
$scopes = [
$scopes
];
}

$scopesForToken = \explode(" ", $result ['scope']);

if (count($misingScopes = array_diff($scopes, $scopesForToken)) > 0 ) {
throw new InvalidAccessTokenException("Missing the following required scopes: " . implode(" ,", $misingScopes));
} else {
Expand All @@ -153,7 +103,7 @@ public function handle($request, Closure $next, ...$scopes)
} catch ( RequestException $e ) {
if ($e->hasResponse()) {
$result = json_decode(( string ) $e->getResponse()->getBody(), true);

if (isset($result ['error'])) {
throw new InvalidAccessTokenException($result ['error'] ['title'] ?? "Invalid token!");
} else {
Expand All @@ -163,7 +113,7 @@ public function handle($request, Closure $next, ...$scopes)
throw new InvalidAccessTokenException($e);
}
}

return $next($request);
}
}

0 comments on commit 9052128

Please sign in to comment.