Symfony 4 Rest API Token Verification calling start method default












1














https://symfony.com/doc/current/security/guard_authentication.html
According to the documentation, the start function would be called if the client accesses a URI/resource that requires authentication, but no authentication details were sent but I have passed the token with the request. I'm not sure where I'm doing wrong, Could anyone please suggest me.. I tried to search a lot but still couldn't find any solutions.



I also tried to print the token on requests and it working fine... so I think the problem is something else, the token is passing well with the request.



if I change the firewall - main - pattern to ^/gateway/v1/ it will give me



Access denied, the user is not fully authenticated; redirecting to authentication entry point.



Output of my Log



 [Mon Nov 19 22:52:34 2018] 127.0.0.1:57773 [401]: /gateway/v1/products
2018-11-19T21:52:39+00:00 [info] Matched route "app_product_products".
2018-11-19T21:52:39+00:00 [debug] Checking for guard authentication credentials.
2018-11-19T21:52:39+00:00 [debug] Calling getCredentials() on guard authenticator.
2018-11-19T21:52:39+00:00 [info] An AuthenticationException was thrown; redirecting to authentication entry point.
2018-11-19T21:52:39+00:00 [debug] Calling Authentication entry point.
[Mon Nov 19 22:52:39 2018] 127.0.0.1:57777 [401]: /gateway/v1/products


TokenController -> Generate the token (http://127.0.0.1:8000/gateway/v1/token)



public function token(Request $request)
{


$data =json_decode($request->getContent(),true);
foreach ($this->getCustomers() as $customer){
if($customer["username"]==$data['username'] && $customer["password"]==$data['password']){
// $token = $this->tokenManager->create($customer["username"]);

// $jwtManager = $this->container->get('lexik_jwt_authentication.jwt_manager');

// return new JsonResponse(['token' => $this->getRandomId()]);

// $token = $this->get('lexik_jwt_authentication.jwt_manager')->create($user);

$token = $this->get('lexik_jwt_authentication.encoder')->encode([
'username' => $customer["username"],
'role' => "IS_AUTHENTICATED_FULLY",
'exp' => time() + 3600 // 1 hour expiration
]);
//$User->setApiToken($token);

return new JsonResponse(['token' => $token]);
}
}
//return $response;
return $this->handleView("Customer Not Exits");
}


config/packages/security.yaml



security:
# ...
#
# encoders:
# AppSecurityUsername:
# algorithm: argon2i

firewalls:

main:
pattern: ^/gateway/v1/token
stateless: true
anonymous: true
json_login:
check_path: /gateway/v1/token
success_handler: lexik_jwt_authentication.handler.authentication_success
failure_handler: lexik_jwt_authentication.handler.authentication_failure

api:
pattern: ^/gateway/v1/
stateless: true
guard:
authenticators:
- jwt_token_authenticator

access_control:
- { path: ^/gateway/v1/token, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/gateway/v1/, roles: IS_AUTHENTICATED_FULLY }
providers:
# used to reload user from session & other features (e.g. switch_user)
app_user_provider:
id: AppSecurityUserProvider


src/Security/JwtTokenAuthenticator.php



<?php

namespace AppSecurity;

use DoctrineORMEntityManager;
use LexikBundleJWTAuthenticationBundleEncoderJWTEncoderInterface;
use LexikBundleJWTAuthenticationBundleExceptionJWTDecodeFailureException;
use LexikBundleJWTAuthenticationBundleTokenExtractorAuthorizationHeaderTokenExtractor;
use SymfonyComponentHttpFoundationJsonResponse;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentSecurityCoreExceptionCustomUserMessageAuthenticationException;
use SymfonyComponentSecurityGuardAbstractGuardAuthenticator;

use SymfonyComponentSecurityCoreAuthenticationTokenTokenInterface;
use SymfonyComponentSecurityCoreExceptionAuthenticationException;
use SymfonyComponentSecurityCoreUserUserInterface;
use SymfonyComponentSecurityCoreUserUserProviderInterface;
use SymfonyComponentHttpFoundationRequest;


class JwtTokenAuthenticator extends AbstractGuardAuthenticator
{

private $jwtEncoder;
private $em;

public function __construct(JWTEncoderInterface $jwtEncoder/*, EntityManager $em*/)
{
$this->jwtEncoder = $jwtEncoder;
/*$this->em = $em;*/
}

public function getCredentials(Request $request)
{
$extractor = new AuthorizationHeaderTokenExtractor(
'Bearer',
'Authorization'
);

$token = $extractor->extract($request);
// return new JsonResponse($token);
if (!$token) {
return new JsonResponse("token not specified") ;
}
return $token;
}
public function getUser($credentials, UserProviderInterface $userProvider)
{
try {
$data = $this->jwtEncoder->decode($credentials);
// return new JsonResponse($data);
} catch (JWTDecodeFailureException $e) {
throw new CustomUserMessageAuthenticationException('Invalid Token');
}

$username = $data['username'];
//$role = $data['role'];
//echo $role;
// $user=new Username();
//return $user->findbyusername($username);

/*return true $this->em
->getRepository('AppBundle:User')
->findOneBy(['username' => $username]);*/

return $userProvider->loadUserByUsername($username);
}
public function checkCredentials($credentials, UserInterface $user)
{
return true;
// TODO: Implement checkCredentials() method.
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
$data = array(
'message' => strtr($exception->getMessageKey(), $exception->getMessageData())

// or to translate this message
// $this->translator->trans($exception->getMessageKey(), $exception->getMessageData())
);

return new JsonResponse($data, Response::HTTP_FORBIDDEN);
// TODO: Implement onAuthenticationFailure() method.
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
return null;
// TODO: Implement onAuthenticationSuccess() method.
}
public function supportsRememberMe()
{
// TODO: Implement supportsRememberMe() method.
}
public function start(Request $request, AuthenticationException $authException = null)
{
$data = array(
// you might translate this message
'message' => 'Authentication Required'
);

return new JsonResponse($data, Response::HTTP_UNAUTHORIZED);
// TODO: Implement start() method.
}
public function supports(Request $request, AuthenticationException $authException = null)
{

if ($request->getPathInfo() != '/gateway/v1/token') {
return false;
}
/*
return new JsonResponse([
'error' => 'auth required'
], 401);

echo "getCredential: ";
$extractor = new AuthorizationHeaderTokenExtractor(
'Bearer',
'Authorization'
);

$token = $extractor->extract($request);
if (!$token) {
return new JsonResponse("token not specified") ;
}
return new JsonResponse($token);
// TODO: Implement start() method.*/
}
}









share|improve this question





























    1














    https://symfony.com/doc/current/security/guard_authentication.html
    According to the documentation, the start function would be called if the client accesses a URI/resource that requires authentication, but no authentication details were sent but I have passed the token with the request. I'm not sure where I'm doing wrong, Could anyone please suggest me.. I tried to search a lot but still couldn't find any solutions.



    I also tried to print the token on requests and it working fine... so I think the problem is something else, the token is passing well with the request.



    if I change the firewall - main - pattern to ^/gateway/v1/ it will give me



    Access denied, the user is not fully authenticated; redirecting to authentication entry point.



    Output of my Log



     [Mon Nov 19 22:52:34 2018] 127.0.0.1:57773 [401]: /gateway/v1/products
    2018-11-19T21:52:39+00:00 [info] Matched route "app_product_products".
    2018-11-19T21:52:39+00:00 [debug] Checking for guard authentication credentials.
    2018-11-19T21:52:39+00:00 [debug] Calling getCredentials() on guard authenticator.
    2018-11-19T21:52:39+00:00 [info] An AuthenticationException was thrown; redirecting to authentication entry point.
    2018-11-19T21:52:39+00:00 [debug] Calling Authentication entry point.
    [Mon Nov 19 22:52:39 2018] 127.0.0.1:57777 [401]: /gateway/v1/products


    TokenController -> Generate the token (http://127.0.0.1:8000/gateway/v1/token)



    public function token(Request $request)
    {


    $data =json_decode($request->getContent(),true);
    foreach ($this->getCustomers() as $customer){
    if($customer["username"]==$data['username'] && $customer["password"]==$data['password']){
    // $token = $this->tokenManager->create($customer["username"]);

    // $jwtManager = $this->container->get('lexik_jwt_authentication.jwt_manager');

    // return new JsonResponse(['token' => $this->getRandomId()]);

    // $token = $this->get('lexik_jwt_authentication.jwt_manager')->create($user);

    $token = $this->get('lexik_jwt_authentication.encoder')->encode([
    'username' => $customer["username"],
    'role' => "IS_AUTHENTICATED_FULLY",
    'exp' => time() + 3600 // 1 hour expiration
    ]);
    //$User->setApiToken($token);

    return new JsonResponse(['token' => $token]);
    }
    }
    //return $response;
    return $this->handleView("Customer Not Exits");
    }


    config/packages/security.yaml



    security:
    # ...
    #
    # encoders:
    # AppSecurityUsername:
    # algorithm: argon2i

    firewalls:

    main:
    pattern: ^/gateway/v1/token
    stateless: true
    anonymous: true
    json_login:
    check_path: /gateway/v1/token
    success_handler: lexik_jwt_authentication.handler.authentication_success
    failure_handler: lexik_jwt_authentication.handler.authentication_failure

    api:
    pattern: ^/gateway/v1/
    stateless: true
    guard:
    authenticators:
    - jwt_token_authenticator

    access_control:
    - { path: ^/gateway/v1/token, roles: IS_AUTHENTICATED_ANONYMOUSLY }
    - { path: ^/gateway/v1/, roles: IS_AUTHENTICATED_FULLY }
    providers:
    # used to reload user from session & other features (e.g. switch_user)
    app_user_provider:
    id: AppSecurityUserProvider


    src/Security/JwtTokenAuthenticator.php



    <?php

    namespace AppSecurity;

    use DoctrineORMEntityManager;
    use LexikBundleJWTAuthenticationBundleEncoderJWTEncoderInterface;
    use LexikBundleJWTAuthenticationBundleExceptionJWTDecodeFailureException;
    use LexikBundleJWTAuthenticationBundleTokenExtractorAuthorizationHeaderTokenExtractor;
    use SymfonyComponentHttpFoundationJsonResponse;
    use SymfonyComponentHttpFoundationResponse;
    use SymfonyComponentSecurityCoreExceptionCustomUserMessageAuthenticationException;
    use SymfonyComponentSecurityGuardAbstractGuardAuthenticator;

    use SymfonyComponentSecurityCoreAuthenticationTokenTokenInterface;
    use SymfonyComponentSecurityCoreExceptionAuthenticationException;
    use SymfonyComponentSecurityCoreUserUserInterface;
    use SymfonyComponentSecurityCoreUserUserProviderInterface;
    use SymfonyComponentHttpFoundationRequest;


    class JwtTokenAuthenticator extends AbstractGuardAuthenticator
    {

    private $jwtEncoder;
    private $em;

    public function __construct(JWTEncoderInterface $jwtEncoder/*, EntityManager $em*/)
    {
    $this->jwtEncoder = $jwtEncoder;
    /*$this->em = $em;*/
    }

    public function getCredentials(Request $request)
    {
    $extractor = new AuthorizationHeaderTokenExtractor(
    'Bearer',
    'Authorization'
    );

    $token = $extractor->extract($request);
    // return new JsonResponse($token);
    if (!$token) {
    return new JsonResponse("token not specified") ;
    }
    return $token;
    }
    public function getUser($credentials, UserProviderInterface $userProvider)
    {
    try {
    $data = $this->jwtEncoder->decode($credentials);
    // return new JsonResponse($data);
    } catch (JWTDecodeFailureException $e) {
    throw new CustomUserMessageAuthenticationException('Invalid Token');
    }

    $username = $data['username'];
    //$role = $data['role'];
    //echo $role;
    // $user=new Username();
    //return $user->findbyusername($username);

    /*return true $this->em
    ->getRepository('AppBundle:User')
    ->findOneBy(['username' => $username]);*/

    return $userProvider->loadUserByUsername($username);
    }
    public function checkCredentials($credentials, UserInterface $user)
    {
    return true;
    // TODO: Implement checkCredentials() method.
    }
    public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
    {
    $data = array(
    'message' => strtr($exception->getMessageKey(), $exception->getMessageData())

    // or to translate this message
    // $this->translator->trans($exception->getMessageKey(), $exception->getMessageData())
    );

    return new JsonResponse($data, Response::HTTP_FORBIDDEN);
    // TODO: Implement onAuthenticationFailure() method.
    }
    public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
    {
    return null;
    // TODO: Implement onAuthenticationSuccess() method.
    }
    public function supportsRememberMe()
    {
    // TODO: Implement supportsRememberMe() method.
    }
    public function start(Request $request, AuthenticationException $authException = null)
    {
    $data = array(
    // you might translate this message
    'message' => 'Authentication Required'
    );

    return new JsonResponse($data, Response::HTTP_UNAUTHORIZED);
    // TODO: Implement start() method.
    }
    public function supports(Request $request, AuthenticationException $authException = null)
    {

    if ($request->getPathInfo() != '/gateway/v1/token') {
    return false;
    }
    /*
    return new JsonResponse([
    'error' => 'auth required'
    ], 401);

    echo "getCredential: ";
    $extractor = new AuthorizationHeaderTokenExtractor(
    'Bearer',
    'Authorization'
    );

    $token = $extractor->extract($request);
    if (!$token) {
    return new JsonResponse("token not specified") ;
    }
    return new JsonResponse($token);
    // TODO: Implement start() method.*/
    }
    }









    share|improve this question



























      1












      1








      1







      https://symfony.com/doc/current/security/guard_authentication.html
      According to the documentation, the start function would be called if the client accesses a URI/resource that requires authentication, but no authentication details were sent but I have passed the token with the request. I'm not sure where I'm doing wrong, Could anyone please suggest me.. I tried to search a lot but still couldn't find any solutions.



      I also tried to print the token on requests and it working fine... so I think the problem is something else, the token is passing well with the request.



      if I change the firewall - main - pattern to ^/gateway/v1/ it will give me



      Access denied, the user is not fully authenticated; redirecting to authentication entry point.



      Output of my Log



       [Mon Nov 19 22:52:34 2018] 127.0.0.1:57773 [401]: /gateway/v1/products
      2018-11-19T21:52:39+00:00 [info] Matched route "app_product_products".
      2018-11-19T21:52:39+00:00 [debug] Checking for guard authentication credentials.
      2018-11-19T21:52:39+00:00 [debug] Calling getCredentials() on guard authenticator.
      2018-11-19T21:52:39+00:00 [info] An AuthenticationException was thrown; redirecting to authentication entry point.
      2018-11-19T21:52:39+00:00 [debug] Calling Authentication entry point.
      [Mon Nov 19 22:52:39 2018] 127.0.0.1:57777 [401]: /gateway/v1/products


      TokenController -> Generate the token (http://127.0.0.1:8000/gateway/v1/token)



      public function token(Request $request)
      {


      $data =json_decode($request->getContent(),true);
      foreach ($this->getCustomers() as $customer){
      if($customer["username"]==$data['username'] && $customer["password"]==$data['password']){
      // $token = $this->tokenManager->create($customer["username"]);

      // $jwtManager = $this->container->get('lexik_jwt_authentication.jwt_manager');

      // return new JsonResponse(['token' => $this->getRandomId()]);

      // $token = $this->get('lexik_jwt_authentication.jwt_manager')->create($user);

      $token = $this->get('lexik_jwt_authentication.encoder')->encode([
      'username' => $customer["username"],
      'role' => "IS_AUTHENTICATED_FULLY",
      'exp' => time() + 3600 // 1 hour expiration
      ]);
      //$User->setApiToken($token);

      return new JsonResponse(['token' => $token]);
      }
      }
      //return $response;
      return $this->handleView("Customer Not Exits");
      }


      config/packages/security.yaml



      security:
      # ...
      #
      # encoders:
      # AppSecurityUsername:
      # algorithm: argon2i

      firewalls:

      main:
      pattern: ^/gateway/v1/token
      stateless: true
      anonymous: true
      json_login:
      check_path: /gateway/v1/token
      success_handler: lexik_jwt_authentication.handler.authentication_success
      failure_handler: lexik_jwt_authentication.handler.authentication_failure

      api:
      pattern: ^/gateway/v1/
      stateless: true
      guard:
      authenticators:
      - jwt_token_authenticator

      access_control:
      - { path: ^/gateway/v1/token, roles: IS_AUTHENTICATED_ANONYMOUSLY }
      - { path: ^/gateway/v1/, roles: IS_AUTHENTICATED_FULLY }
      providers:
      # used to reload user from session & other features (e.g. switch_user)
      app_user_provider:
      id: AppSecurityUserProvider


      src/Security/JwtTokenAuthenticator.php



      <?php

      namespace AppSecurity;

      use DoctrineORMEntityManager;
      use LexikBundleJWTAuthenticationBundleEncoderJWTEncoderInterface;
      use LexikBundleJWTAuthenticationBundleExceptionJWTDecodeFailureException;
      use LexikBundleJWTAuthenticationBundleTokenExtractorAuthorizationHeaderTokenExtractor;
      use SymfonyComponentHttpFoundationJsonResponse;
      use SymfonyComponentHttpFoundationResponse;
      use SymfonyComponentSecurityCoreExceptionCustomUserMessageAuthenticationException;
      use SymfonyComponentSecurityGuardAbstractGuardAuthenticator;

      use SymfonyComponentSecurityCoreAuthenticationTokenTokenInterface;
      use SymfonyComponentSecurityCoreExceptionAuthenticationException;
      use SymfonyComponentSecurityCoreUserUserInterface;
      use SymfonyComponentSecurityCoreUserUserProviderInterface;
      use SymfonyComponentHttpFoundationRequest;


      class JwtTokenAuthenticator extends AbstractGuardAuthenticator
      {

      private $jwtEncoder;
      private $em;

      public function __construct(JWTEncoderInterface $jwtEncoder/*, EntityManager $em*/)
      {
      $this->jwtEncoder = $jwtEncoder;
      /*$this->em = $em;*/
      }

      public function getCredentials(Request $request)
      {
      $extractor = new AuthorizationHeaderTokenExtractor(
      'Bearer',
      'Authorization'
      );

      $token = $extractor->extract($request);
      // return new JsonResponse($token);
      if (!$token) {
      return new JsonResponse("token not specified") ;
      }
      return $token;
      }
      public function getUser($credentials, UserProviderInterface $userProvider)
      {
      try {
      $data = $this->jwtEncoder->decode($credentials);
      // return new JsonResponse($data);
      } catch (JWTDecodeFailureException $e) {
      throw new CustomUserMessageAuthenticationException('Invalid Token');
      }

      $username = $data['username'];
      //$role = $data['role'];
      //echo $role;
      // $user=new Username();
      //return $user->findbyusername($username);

      /*return true $this->em
      ->getRepository('AppBundle:User')
      ->findOneBy(['username' => $username]);*/

      return $userProvider->loadUserByUsername($username);
      }
      public function checkCredentials($credentials, UserInterface $user)
      {
      return true;
      // TODO: Implement checkCredentials() method.
      }
      public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
      {
      $data = array(
      'message' => strtr($exception->getMessageKey(), $exception->getMessageData())

      // or to translate this message
      // $this->translator->trans($exception->getMessageKey(), $exception->getMessageData())
      );

      return new JsonResponse($data, Response::HTTP_FORBIDDEN);
      // TODO: Implement onAuthenticationFailure() method.
      }
      public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
      {
      return null;
      // TODO: Implement onAuthenticationSuccess() method.
      }
      public function supportsRememberMe()
      {
      // TODO: Implement supportsRememberMe() method.
      }
      public function start(Request $request, AuthenticationException $authException = null)
      {
      $data = array(
      // you might translate this message
      'message' => 'Authentication Required'
      );

      return new JsonResponse($data, Response::HTTP_UNAUTHORIZED);
      // TODO: Implement start() method.
      }
      public function supports(Request $request, AuthenticationException $authException = null)
      {

      if ($request->getPathInfo() != '/gateway/v1/token') {
      return false;
      }
      /*
      return new JsonResponse([
      'error' => 'auth required'
      ], 401);

      echo "getCredential: ";
      $extractor = new AuthorizationHeaderTokenExtractor(
      'Bearer',
      'Authorization'
      );

      $token = $extractor->extract($request);
      if (!$token) {
      return new JsonResponse("token not specified") ;
      }
      return new JsonResponse($token);
      // TODO: Implement start() method.*/
      }
      }









      share|improve this question















      https://symfony.com/doc/current/security/guard_authentication.html
      According to the documentation, the start function would be called if the client accesses a URI/resource that requires authentication, but no authentication details were sent but I have passed the token with the request. I'm not sure where I'm doing wrong, Could anyone please suggest me.. I tried to search a lot but still couldn't find any solutions.



      I also tried to print the token on requests and it working fine... so I think the problem is something else, the token is passing well with the request.



      if I change the firewall - main - pattern to ^/gateway/v1/ it will give me



      Access denied, the user is not fully authenticated; redirecting to authentication entry point.



      Output of my Log



       [Mon Nov 19 22:52:34 2018] 127.0.0.1:57773 [401]: /gateway/v1/products
      2018-11-19T21:52:39+00:00 [info] Matched route "app_product_products".
      2018-11-19T21:52:39+00:00 [debug] Checking for guard authentication credentials.
      2018-11-19T21:52:39+00:00 [debug] Calling getCredentials() on guard authenticator.
      2018-11-19T21:52:39+00:00 [info] An AuthenticationException was thrown; redirecting to authentication entry point.
      2018-11-19T21:52:39+00:00 [debug] Calling Authentication entry point.
      [Mon Nov 19 22:52:39 2018] 127.0.0.1:57777 [401]: /gateway/v1/products


      TokenController -> Generate the token (http://127.0.0.1:8000/gateway/v1/token)



      public function token(Request $request)
      {


      $data =json_decode($request->getContent(),true);
      foreach ($this->getCustomers() as $customer){
      if($customer["username"]==$data['username'] && $customer["password"]==$data['password']){
      // $token = $this->tokenManager->create($customer["username"]);

      // $jwtManager = $this->container->get('lexik_jwt_authentication.jwt_manager');

      // return new JsonResponse(['token' => $this->getRandomId()]);

      // $token = $this->get('lexik_jwt_authentication.jwt_manager')->create($user);

      $token = $this->get('lexik_jwt_authentication.encoder')->encode([
      'username' => $customer["username"],
      'role' => "IS_AUTHENTICATED_FULLY",
      'exp' => time() + 3600 // 1 hour expiration
      ]);
      //$User->setApiToken($token);

      return new JsonResponse(['token' => $token]);
      }
      }
      //return $response;
      return $this->handleView("Customer Not Exits");
      }


      config/packages/security.yaml



      security:
      # ...
      #
      # encoders:
      # AppSecurityUsername:
      # algorithm: argon2i

      firewalls:

      main:
      pattern: ^/gateway/v1/token
      stateless: true
      anonymous: true
      json_login:
      check_path: /gateway/v1/token
      success_handler: lexik_jwt_authentication.handler.authentication_success
      failure_handler: lexik_jwt_authentication.handler.authentication_failure

      api:
      pattern: ^/gateway/v1/
      stateless: true
      guard:
      authenticators:
      - jwt_token_authenticator

      access_control:
      - { path: ^/gateway/v1/token, roles: IS_AUTHENTICATED_ANONYMOUSLY }
      - { path: ^/gateway/v1/, roles: IS_AUTHENTICATED_FULLY }
      providers:
      # used to reload user from session & other features (e.g. switch_user)
      app_user_provider:
      id: AppSecurityUserProvider


      src/Security/JwtTokenAuthenticator.php



      <?php

      namespace AppSecurity;

      use DoctrineORMEntityManager;
      use LexikBundleJWTAuthenticationBundleEncoderJWTEncoderInterface;
      use LexikBundleJWTAuthenticationBundleExceptionJWTDecodeFailureException;
      use LexikBundleJWTAuthenticationBundleTokenExtractorAuthorizationHeaderTokenExtractor;
      use SymfonyComponentHttpFoundationJsonResponse;
      use SymfonyComponentHttpFoundationResponse;
      use SymfonyComponentSecurityCoreExceptionCustomUserMessageAuthenticationException;
      use SymfonyComponentSecurityGuardAbstractGuardAuthenticator;

      use SymfonyComponentSecurityCoreAuthenticationTokenTokenInterface;
      use SymfonyComponentSecurityCoreExceptionAuthenticationException;
      use SymfonyComponentSecurityCoreUserUserInterface;
      use SymfonyComponentSecurityCoreUserUserProviderInterface;
      use SymfonyComponentHttpFoundationRequest;


      class JwtTokenAuthenticator extends AbstractGuardAuthenticator
      {

      private $jwtEncoder;
      private $em;

      public function __construct(JWTEncoderInterface $jwtEncoder/*, EntityManager $em*/)
      {
      $this->jwtEncoder = $jwtEncoder;
      /*$this->em = $em;*/
      }

      public function getCredentials(Request $request)
      {
      $extractor = new AuthorizationHeaderTokenExtractor(
      'Bearer',
      'Authorization'
      );

      $token = $extractor->extract($request);
      // return new JsonResponse($token);
      if (!$token) {
      return new JsonResponse("token not specified") ;
      }
      return $token;
      }
      public function getUser($credentials, UserProviderInterface $userProvider)
      {
      try {
      $data = $this->jwtEncoder->decode($credentials);
      // return new JsonResponse($data);
      } catch (JWTDecodeFailureException $e) {
      throw new CustomUserMessageAuthenticationException('Invalid Token');
      }

      $username = $data['username'];
      //$role = $data['role'];
      //echo $role;
      // $user=new Username();
      //return $user->findbyusername($username);

      /*return true $this->em
      ->getRepository('AppBundle:User')
      ->findOneBy(['username' => $username]);*/

      return $userProvider->loadUserByUsername($username);
      }
      public function checkCredentials($credentials, UserInterface $user)
      {
      return true;
      // TODO: Implement checkCredentials() method.
      }
      public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
      {
      $data = array(
      'message' => strtr($exception->getMessageKey(), $exception->getMessageData())

      // or to translate this message
      // $this->translator->trans($exception->getMessageKey(), $exception->getMessageData())
      );

      return new JsonResponse($data, Response::HTTP_FORBIDDEN);
      // TODO: Implement onAuthenticationFailure() method.
      }
      public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
      {
      return null;
      // TODO: Implement onAuthenticationSuccess() method.
      }
      public function supportsRememberMe()
      {
      // TODO: Implement supportsRememberMe() method.
      }
      public function start(Request $request, AuthenticationException $authException = null)
      {
      $data = array(
      // you might translate this message
      'message' => 'Authentication Required'
      );

      return new JsonResponse($data, Response::HTTP_UNAUTHORIZED);
      // TODO: Implement start() method.
      }
      public function supports(Request $request, AuthenticationException $authException = null)
      {

      if ($request->getPathInfo() != '/gateway/v1/token') {
      return false;
      }
      /*
      return new JsonResponse([
      'error' => 'auth required'
      ], 401);

      echo "getCredential: ";
      $extractor = new AuthorizationHeaderTokenExtractor(
      'Bearer',
      'Authorization'
      );

      $token = $extractor->extract($request);
      if (!$token) {
      return new JsonResponse("token not specified") ;
      }
      return new JsonResponse($token);
      // TODO: Implement start() method.*/
      }
      }






      rest jwt symfony4 lexikjwtauthbundle jwt-auth






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 19 at 23:32

























      asked Nov 19 at 22:25









      PANKAJ NAROLA

      668




      668





























          active

          oldest

          votes











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53383531%2fsymfony-4-rest-api-token-verification-calling-start-method-default%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown






























          active

          oldest

          votes













          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53383531%2fsymfony-4-rest-api-token-verification-calling-start-method-default%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          If I really need a card on my start hand, how many mulligans make sense? [duplicate]

          Alcedinidae

          Can an atomic nucleus contain both particles and antiparticles? [duplicate]