Check JWT (Firebase) Token with Symfony 5.3

FourBars

I'm working on an API, and I had implemented a JWT to make it stateless. I created an AuthController, which returns a JWT when login information is correct. Here you can see the return code that generates the token:

/* RETURN MESSAGE */
$body = [
    'auth_token' => $jwt,
];
$json = new JsonResponse($body);
$json->setStatusCode(201, "Created");   // Headers
return $json;

This is the result when I run the authenticate method, un the URL localhost:8000/authenticate.
Now, what I would need to do is that, when a user tries to get another / URL, the program doesn't allow him to reach it if he's not passing the Bearer token in the request's header. But it's not working. The platform always allows me to enter any URL without setting an Authorization in the header.
Here's my security file, where I tried to set this:

security:
    # https://symfony.com/doc/current/security/authenticator_manager.html
    enable_authenticator_manager: true

    # https://symfony.com/doc/current/security.html#c-hashing-passwords
    password_hashers:
        Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: 'auto'

    encoders:
        App\Entity\ATblUsers:
            algorithm: bcrypt

    providers:
        users_in_memory: { memory: null }

    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false

        main:
            # Anonymous property is no longer supported by Symfony. It is commented by now, but it will be deleted in
            # future revision:
            # anonymous: true
            guard:
                authenticators:
                    - App\Security\JwtAuthenticator
            lazy: true
            provider: users_in_memory

            # activate different ways to authenticate
            # https://symfony.com/doc/current/security.html#firewalls-authentication

            # https://symfony.com/doc/current/security/impersonating_user.html
            # switch_user: true
            stateless: true

    # Easy way to control access for large sections of your site
    # Note: Only the *first* access control that matches will be used
    access_control:
        # - { path: ^/admin, roles: ROLE_ADMIN }
        # - { path: ^/profile, roles: ROLE_USER }

And, finally, here's my App\Security\JwtAuthenticator:

namespace App\Security;

use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\DependencyInjection\ParameterBag\ContainerBagInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Firebase\JWT\JWT;
use Symfony\Component\Security\Guard\AbstractGuardAuthenticator;

class JwtAuthenticator extends AbstractGuardAuthenticator
{
    private $em;
    private $params;

    public function __construct(EntityManagerInterface $em, ContainerBagInterface $params)
    {
        $this->em = $em;
        $this->params = $params;
    }

    public function start(Request $request, AuthenticationException $authException = null): JsonResponse
    {
        $body = [
            'message' => 'Authentication Required',
        ];
        return new JsonResponse($body, Response::HTTP_UNAUTHORIZED);
    }

    public function supports(Request $request): bool
    {
        return $request->headers->has('Authorization');
    }

    public function getCredentials(Request $request)
    {
        return $request->headers->get('Authorization');
    }

    public function getUser($credentials, UserProviderInterface $userProvider)
    {
        try{
            $credentials = str_replace('Bearer ', '', $credentials);
            $jwt = (array) JWT::decode($credentials, $this->params->get('jwt_secret'), ['HS256']);
            return $this->em->getRepository('App:ATblUsers')->find($jwt['sub']);
        }catch (\Exception $exception){
            throw new AuthenticationException($exception->getMessage());
        }

    }

    public function checkCredentials($credentials, UserInterface $user)
    {

    }

    public function onAuthenticationFailure(Request $request, AuthenticationException $exception): JsonResponse
    {
        return new JsonResponse([
            'message' => $exception->getMessage()
        ], Response::HTTP_UNAUTHORIZED);
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $providerKey)
    {
        return;
    }

    public function supportsRememberMe(): bool
    {
        return false;
    }
}

I've been looking at a lot of websites and tutorials, but not anyone is doing exactly what I need or are implementing very basic functionalities that don't match with what I need. Almost all of that websites explain this using Symfony 4, but I'm using Symfony 5, so a lot of functions that use in tutorials are deprecated. Does someone know what I am missing?

Slimu

You are probably missing access_control configuration in security.yaml:

security:
    # https://symfony.com/doc/current/security/authenticator_manager.html
    enable_authenticator_manager: true

    # https://symfony.com/doc/current/security.html#c-hashing-passwords
    password_hashers:
        Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: 'auto'

    encoders:
        App\Entity\ATblUsers:
            algorithm: bcrypt

    providers:
        users_in_memory: { memory: null }

    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false

        main:
            # Anonymous property is no longer supported by Symfony. It is commented by now, but it will be deleted in
            # future revision:
            # anonymous: true
            guard:
                authenticators:
                    - App\Security\JwtAuthenticator
            lazy: true
            provider: users_in_memory

            # activate different ways to authenticate
            # https://symfony.com/doc/current/security.html#firewalls-authentication

            # https://symfony.com/doc/current/security/impersonating_user.html
            # switch_user: true
            stateless: true

    # Easy way to control access for large sections of your site
    # Note: Only the *first* access control that matches will be used
    access_control:
        - { path: ^/authenticate, roles: PUBLIC_ACCESS }
        - { path: ^/, roles: IS_AUTHENTICATED_FULLY }

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

check if bearer token is jwt or not

jwt check if token expired

Symfony JWT Bundle responding with JWT Token not found

Symfony JWT token: exception when token is expired

How to check JWT token validity

AuthGuard: OnAuthStateChanged VS check token in Angular 5 + Firebase

Is it useful to use CSRF token protection for Symfony 3 API REST and Angular webapp with JWT?

Retrieve data from Jwt Token - Flutter and Symfony

Firebase php-jwt Token Refresh

Firebase JWT Authentication, Continually Send Token?

How to verify firebase ID token with PHP(JWT)?

Firebase admin sdk unable to decode jwt token

Firebase ID Token has invalid signature (JWT)

Check if Firebase registration token is invalid

Firebase JWT library can't verify Python JWT token

Angular 5 Http Interceptor refreshing JWT token

Firebase App Check and reCAPTCHA v3 Enterprise Integration: Billing and Token Reusability

JWT Token generated using firebase/php-jwt is showing as Invalid Token

Java Spring Resource Server seems to check JWT token on response

Check JWT token exists in memory cache before executing the codes in the API

Best way to check jwt token expire status if stored in localstorage

JWT Token: logout JWT token

Firebase & Postman | Generate JWT for Google Identity OAuth 2.0 token

Is it possible to validate a firebase token (JWT) from server (Java)

Is the length of a Firebase Auth JWT Token always 1250 characters?

PHP Slim 4 - Authorize api request using firebase JWT token

How to properly supply legacy Firebase JWT token as "auth" to the REST API?

Firebase Invalid registration token. Check the token format

Symfony3 Service and Token Storage

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    pump.io port in URL

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    flutter: dropdown item programmatically unselect problem

  14. 14

    How to use merge windows unallocated space into Ubuntu using GParted?

  15. 15

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  16. 16

    Nuget add packages gives access denied errors

  17. 17

    Svchost high CPU from Microsoft.BingWeather app errors

  18. 18

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  19. 19

    12.04.3--- Dconf Editor won't show com>canonical>unity option

  20. 20

    Any way to remove trailing whitespace *FOR EDITED* lines in Eclipse [for Java]?

  21. 21

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

HotTag

Archive