Skip to content

Commit

Permalink
Merge pull request #40 from auth0/3.x.x-dev
Browse files Browse the repository at this point in the history
New optional jwt middleware
  • Loading branch information
glena authored Jul 11, 2016
2 parents b098579 + 935ab4d commit e4d1f6b
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 21 deletions.
49 changes: 28 additions & 21 deletions src/Auth0/Login/Middleware/Auth0JWTMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,37 +12,44 @@ public function __construct(Auth0UserRepository $userRepository) {
$this->userRepository = $userRepository;
}

protected function getToken($request) {
// Get the encrypted user JWT
$authorizationHeader = $request->header("Authorization");
return trim(str_replace('Bearer ', '', $authorizationHeader));
}

protected function validateToken($token) {
return ($token !== '');
}

public function handle($request, \Closure $next)
{
$auth0 = \App::make('auth0');

// Get the encrypted user JWT
$authorizationHeader = $request->header("Authorization");
$encUser = str_replace('Bearer ', '', $authorizationHeader);

if (trim($encUser) == '') {
$token = $this->getToken($request);

if ( ! $this->validateToken($token)) {
return \Response::make("Unauthorized user", 401);
}

try {
$jwtUser = $auth0->decodeJWT($encUser);
}
catch(CoreException $e) {
return \Response::make("Unauthorized user", 401);
}
catch(Exception $e) {
echo $e;exit;
}
if ($token) {
try {
$jwtUser = $auth0->decodeJWT($token);
}
catch(CoreException $e) {
return \Response::make("Unauthorized user", 401);
}

// if it does not represent a valid user, return a HTTP 401
$user = $this->userRepository->getUserByDecodedJWT($jwtUser);
// if it does not represent a valid user, return a HTTP 401
$user = $this->userRepository->getUserByDecodedJWT($jwtUser);

if (!$user) {
return \Response::make("Unauthorized user", 401);
}
if (!$user) {
return \Response::make("Unauthorized user", 401);
}

// lets log the user in so it is accessible
\Auth::login($user);
// lets log the user in so it is accessible
\Auth::login($user);
}

// continue the execution
return $next($request);
Expand Down
9 changes: 9 additions & 0 deletions src/Auth0/Login/Middleware/Auth0OptionalJWTMiddleware.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?php namespace Auth0\Login\Middleware;

class Auth0OptionalJWTMiddleware extends Auth0JWTMiddleware {

protected function validateToken($token) {
return true;
}

}
14 changes: 14 additions & 0 deletions src/Auth0/Login/Middleware/ForceAuthMiddleware.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<?php namespace Auth0\Login\Middleware;

class ForceAuthMiddleware {

public function handle($request, \Closure $next)
{
if ( ! \Auth::check()) {
return \Response::make("Unauthorized user", 401);
}

return $next($request);
}

}

0 comments on commit e4d1f6b

Please sign in to comment.