PHP Snippet 1: `# Symfony 3.4 security.yml
security:
encoders:
FOS\UserBundle\Model\UserInterface: bcrypt
Symfony\Component\Security\Core\User\User: plaintext
role_hierarchy:
ROLE_ADMIN: ROLE_USER
ROLE_SUPER_ADMIN: ROLE_ADMIN
ROLE_API: ROLE_USER, ROLE_MEDIC, ROLE_STUDENT
providers:
fos_userbundle:
id: fos_user.user_provider.username_email
in_memory:
memory: ~
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
api_login:
pattern: ^/api/login
stateless: true
anonymous: true
form_login:
check_path: /api/login_check
success_handler: lexik_jwt_authentication.handler.authentication_success
failure_handler: lexik_jwt_authentication.handler.authentication_failure
require_previous_session: false
api:
pattern: ^/(api)
stateless: true
anonymous: ~
guard:
authenticators:
- lexik_jwt_authentication.jwt_token_authenticator
provider: fos_userbundle
access_control: .................`
Copy PHP Snippet 2:
namespace AppBundle \Document ;
use Doctrine \ODM \MongoDB \Mapping \Annotations as MongoDB ;
use FOS \UserBundle \Model \User as BaseUser ;
use Symfony \Component \Validator \Constraints as Assert ;
use Doctrine \Bundle \MongoDBBundle \Validator \Constraints \Unique as MongoDBUnique ;
class User implements BaseUser
{
protected $id ;
protected $email ;
protected $username ;
protected $password ;
private $isActive ;
public function __construct ( )
{
var_dump ("1" );
$this ->isActive = true ;
}
public function getId ( )
{
return $this ->id;
}
public function getEmail ( )
{
return $this ->email;
}
public function setEmail ($email )
{
$this ->email = $email ;
}
public function setUsername ($username )
{
$this ->username = $username ;
}
public function getUsername ( )
{
var_dump ($this ->username);
return $this ->username;
}
public function getSalt ( )
{
return null ;
}
public function getPassword ( )
{
return $this ->password;
}
public function setPassword ($password )
{
$this ->password = $password ;
}
public function getRoles ( )
{
return array ('ROLE_USER' );
}
public function eraseCredentials ( )
{
}
}
Copy PHP Snippet 3: namespace \your_namespace \Api ;
use FOS \RestBundle \Context \Context ;
use FOS \RestBundle \Controller \Annotations as Rest ;
use FOS \RestBundle \Controller \FOSRestController ;
use AppBundle \Document \User ;
use Symfony \Bundle \FrameworkBundle \Controller \Controller ;
use Sensio \Bundle \FrameworkExtraBundle \Configuration \Method ;
use Sensio \Bundle \FrameworkExtraBundle \Configuration \Route ;
use Sensio \Bundle \FrameworkExtraBundle \Configuration \Security ;
use Symfony \Component \HttpFoundation \Request ;
use Symfony \Component \HttpFoundation \Response ;
use Symfony \Component \HttpFoundation \JsonResponse ;
use Symfony \Component \HttpKernel \Exception \NotFoundHttpException ;
use Symfony \Component \Security \Core \Encoder \EncoderFactory ;
use Symfony \Component \Security \Core \Exception \BadCredentialsException ;
use Symfony \Component \EventDispatcher \EventDispatcher ;
use Symfony \Component \Security \Core \Authentication \Token \UsernamePasswordToken ;
use Symfony \Component \Security \Http \Event \InteractiveLoginEvent ;
use Lexik \Bundle \JWTAuthenticationBundle \Exception \ExpiredTokenException ;
use Lexik \Bundle \JWTAuthenticationBundle \Exception \InvalidTokenException ;
use Lexik \Bundle \JWTAuthenticationBundle \Exception \JWTDecodeFailureException ;
use Lexik \Bundle \JWTAuthenticationBundle \Security \Authentication \Token \PreAuthenticationJWTUserToken ;
use Nelmio \ApiDocBundle \Annotation \ApiDoc ;
class TokenController extends FOSRestController
{
public function newTokenAction (Request $request )
{
$em = $this ->getDoctrine ()->getManager ();
$username = $request ->get ('username' );
$user = $em ->getRepository ('AppBundle:User' )->findOneBy (['email' => $username ]);
if (!$user ) {
throw $this ->createNotFoundException ();
}
if (!$user ->isEnabled ()){
throw $this ->createNotFoundException ($this ->get ('translator' )->trans ('security.user_is_disabled' ));
}
$pass = $request ->get ('pass' );
$isValid = $this ->get ('security.password_encoder' )->isPasswordValid ($user , $pass );
if (!$isValid ) {
throw new BadCredentialsException ();
}
$token = $this ->get ('lexik_jwt_authentication.encoder' )->encode ([
'username' => $user ->getUsername (),
'id' => $user ->getId (),
'roles' => $user ->getRoles (),
'exp' => time () + (30 * 24 * 3600 )
]);
$tokenLogin = new UsernamePasswordToken ($user , $pass , "public" , $user ->getRoles ());
$this ->get ("security.token_storage" )->setToken ($tokenLogin );
$event = new InteractiveLoginEvent ($request , $tokenLogin );
$this ->get ("event_dispatcher" )->dispatch ("security.interactive_login" , $event );
$view = $this ->view ([
'token' => $token ,
'user' => $user
]);
$context = new Context ();
$context ->addGroups (['Public' ]);
$view ->setContext ($context );
return $this ->handleView ($view );
}
public function validateUserToken (Request $request )
{
$token = $request ->get ('token' );
$fos = $this ->get ('fos_user.user_provider.username_email' );
$preAuthToken = new PreAuthenticationJWTUserToken ($token );
try {
if (!$payload = $this ->get ('lexik_jwt_authentication.jwt_manager' )->decode ($preAuthToken )) {
throw new InvalidTokenException ('Invalid JWT Token' );
}
$preAuthToken ->setPayload ($payload );
} catch (JWTDecodeFailureException $e ) {
if (JWTDecodeFailureException ::EXPIRED_TOKEN === $e ->getReason ()) {
throw new ExpiredTokenException ();
}
throw new InvalidTokenException ('Invalid JWT Token' , 0 , $e );
}
$user = $this ->get ('lexik_jwt_authentication.security.guard.jwt_token_authenticator' )->getUser ($preAuthToken , $fos );
$view = $this ->view ([
'token' => $token ,
'user' => $user
]);
$context = new Context ();
$context ->addGroups (array_merge (['Public' ],$user ->getRoles ()));
$view ->setContext ($context );
return $this ->handleView ($view );
}
Copy