You've already forked Php-Template
feat: implement JWT authentication and scope validation middleware #11
@@ -6,8 +6,7 @@ namespace Siteworxpro\App\Controllers;
|
||||
|
||||
use Nyholm\Psr7\ServerRequest;
|
||||
use Psr\Http\Message\ResponseInterface;
|
||||
use Siteworxpro\App\Annotations\Guards\Jwt;
|
||||
use Siteworxpro\App\Annotations\Guards\Scope;
|
||||
use Siteworxpro\App\Annotations\Guards;
|
||||
use Siteworxpro\App\Http\JsonResponseFactory;
|
||||
|
||||
/**
|
||||
@@ -22,8 +21,8 @@ class IndexController extends Controller
|
||||
*
|
||||
* @throws \JsonException
|
||||
*/
|
||||
#[Jwt]
|
||||
#[Scope(['get.index'])]
|
||||
#[Guards\Jwt]
|
||||
#[Guards\Scope(['get.index'])]
|
||||
public function get(ServerRequest $request): ResponseInterface
|
||||
{
|
||||
return JsonResponseFactory::createJsonResponse(['status_code' => 200, 'message' => 'Server is running']);
|
||||
@@ -32,8 +31,8 @@ class IndexController extends Controller
|
||||
/**
|
||||
* @throws \JsonException
|
||||
*/
|
||||
#[Jwt]
|
||||
#[Scope(['post.index'])]
|
||||
#[Guards\Jwt]
|
||||
#[Guards\Scope(['post.index'])]
|
||||
public function post(ServerRequest $request): ResponseInterface
|
||||
{
|
||||
return JsonResponseFactory::createJsonResponse(['status_code' => 200, 'message' => 'Server is running']);
|
||||
|
||||
@@ -10,6 +10,7 @@ use Lcobucci\JWT\JwtFacade;
|
||||
use Lcobucci\JWT\Signer\Hmac\Sha256 as Hmac256;
|
||||
use Lcobucci\JWT\Signer\Key\InMemory;
|
||||
use Lcobucci\JWT\Signer\Rsa\Sha256;
|
||||
use Lcobucci\JWT\Token\InvalidTokenStructure;
|
||||
use Lcobucci\JWT\Validation\Constraint\IssuedBy;
|
||||
use Lcobucci\JWT\Validation\Constraint\LooseValidAt;
|
||||
use Lcobucci\JWT\Validation\Constraint\PermittedFor;
|
||||
@@ -99,6 +100,11 @@ class JwtMiddleware implements MiddlewareInterface
|
||||
'message' => 'Unauthorized: Invalid token',
|
||||
'errors' => $violations
|
||||
], CodesEnum::UNAUTHORIZED);
|
||||
} catch (InvalidTokenStructure) {
|
||||
return JsonResponseFactory::createJsonResponse([
|
||||
'status_code' => 401,
|
||||
'message' => 'Unauthorized: Invalid token',
|
||||
], CodesEnum::UNAUTHORIZED);
|
||||
}
|
||||
|
||||
foreach ($jwt->claims()->all() as $item => $value) {
|
||||
|
||||
Reference in New Issue
Block a user