K
K
Konstantin Zhikhor2021-01-01 21:39:58
symfony
Konstantin Zhikhor, 2021-01-01 21:39:58

How to create rest API authentication in Symfony?

Tell me please. How to create an authentication? How to apply the token correctly?
I tried to follow this documentation https://symfony.com/doc/current/security.html#auth...

namespace App\Controller;

use App\Entity\User;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Attribute\CurrentUser;

/**
 * The class is for api login
 */
class ApiLoginController extends AbstractController
{
    #[Route('/api/login', name: 'api_login')]
    public function index(#[CurrentUser] ?User $user): Response
    {
        if (null === $user) {
            return $this->json([
                'message' => 'missing credentials',
            ], Response::HTTP_UNAUTHORIZED);
        }
        
        return $this->json([
            'user'  => $user->getUserIdentifier(),
        ]);
    }
}

In this class, I'm trying to log in. And everything seems to be ok.
But as in another class I try to get an authorized user, the result is empty.
For example
class NewsController extends AbstractController
{
    #[Route('/news', name: 'news')]
    public function index(): Response
    {
        /** @var User $user */
        $user = $this->getUser();
        die(print_r($user));
        return $this->json([
            'message' => 'Welcome to your new controller!',
            'path' => 'src/Controller/NewsController.php',
        ]);
    }
}

Security.yaml
security:
    enable_authenticator_manager: true
    # https://symfony.com/doc/current/security.html#registering-the-user-hashing-passwords
    password_hashers:
        Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface: 'auto'
        App\Entity\User:
            algorithm: auto

    # https://symfony.com/doc/current/security.html#loading-the-user-the-user-provider
    providers:
        # used to reload user from session & other features (e.g. switch_user)
        app_user_provider:
            entity:
                class: App\Entity\User
                property: username
    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        main:
            lazy: true
            provider: app_user_provider
            json_login:
                # api_login is a route we will create below
                check_path: api_login
            logout:
                path: app_logout

Help me please.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question