We will follow 4 steps to implement JWT token in API
-
- Install a package to encode and decode JWT token
- Create a public and a private key to verify and for encode JWT token.
- Change middleware.
- Update login function.Install a package to encode and decode JWT tokenWe will use below package
Link : https://github.com/firebase/php-jwt
To install this package you have to give below composer commandcomposer require firebase/php-jwt
Create a public and a private key to verify and for encode JWT token.
To generate public and private key in project directory we give below commands
# generate private key openssl genrsa -out config/jwt.key 1024 # generate public key openssl rsa -in config/jwt.key -outform PEM -pubout -out config/jwt.pem
Change middleware
public function getAuthenticationService(ServerRequestInterface $request): AuthenticationServiceInterface { $service = newAuthenticationService(); $fields = [ IdentifierInterface::CREDENTIAL_USERNAME => 'email', IdentifierInterface::CREDENTIAL_PASSWORD => 'password' ]; $service->loadIdentifier('Authentication.Password', [ 'returnPayload' => false, 'fields' => $fields, ]); $service->loadAuthenticator('Authentication.Form', [ 'fields' => $fields, ]); if($request->getParam('prefix') === 'Api'){ $service->loadIdentifier('Authentication.JwtSubject'); $service->loadAuthenticator('Authentication.Jwt', [ 'secretKey' => file_get_contents(CONFIG .'/jwt.pem'), 'algorithm' => 'RS256', 'returnPayload' => false ]); }else{ $service->setConfig([ 'unauthenticatedRedirect' => Router::url('/login'), 'queryParam' => 'redirect', ]); $service->loadAuthenticator('Authentication.Session'); } return$service; }
Changing login method :
public function login() { $result = $this->Authentication->getResult(); if( $result->isValid() ) { $user = $result->getData(); $privateKey = file_get_contents(CONFIG .'/jwt.key'); $payload = [ 'sub' => $user->id, 'exp' => time()+60 ]; $user = [ 'token' => JWT::encode($payload,$privateKey,'RS256'), 'userEnt' => $user ]; }else{ $this->response = $this->response->withStatus(401); $user = [ 'message' => 'invalid user' ]; } $this->set('user',$user); $this->viewBuilder()->setOption('serialize','user'); }
That’s it.